In this blogpost I am going to show you how to add a button which takes user to the top of the current page if the user has scrolled down to read any article. I am going to use JavaScript and CSS to set the button. Let’s add step by step code and create the full functioning button. First, lets add simple HTML button in your page.
In above HTML code I have just added simple HTML button with id and onclick event handler. Which is just basic HTML code. Now, let’s add some CSS style to set the button’s position on different page movements.
In the style above, I have kept the button hidden by using display property and I’ll use JavaScript to change that display style later on. To set the button on the bottom of the page I’ve set bottom property as well and I’ve kept the position property fixed as I want the button to be stedy on the page while user reads the article and not scroll down and disappear! That would not make any sense!
Similarly, I am setting the right property so set the button on a proper position on a page. Button’s z-index property is 99 because I don’t want it to overlap with any other elements and be in front of all the elements, clearly visible. I have removed border and outline but you can keep it to give the button a different look, it’s up to you.
I’ve set the color and background-color properties as per the color combination of my pages so that’s up to you to decide what color you should go for. Also for, padding, border-radius and font-size, you can choose your own style. I have added cursor property as a pointer to add a mouse pointer on hover. Also, I am changing the color of the button on mouse hover.
Now you have an idea about the position of the button. All we need is to show and hide the button when user scrolls down and up. I’ll do that using JavaScript.
In the JavaScript code above, I’m calling a function on the window.scroll event. In that function, I am checking if the user scrolls 20px or more from the top using document.body.scrollTop. If that condition is true then I am changing the button’s display from none to block and in else condition I am changing it back to none. So now we have a working button which will be displayed when user scrolls down 20px or more.
What we need is one more function to tell the browser to go to top position on the page. For that we are using button’s onclick event and calling a function GoTopFunction and setting the same document.body.scrollTop to 0px aka to the top of the page.
go to top scroll