
In this tutorial, I’m going to show you how to create a scroll Back to top button, so when the user scrolls down 100 px from the top of the document the button appears, and when the user clicks on the button scroll to the top of the page.
So let’s dive into the step-by-step tutorial.
Step 1: Add HTML Back to Top Button
First Create a button and give it an id of mybtn :
<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>
Step 2: Style scroll button css
Hide the Button by default, using the CSS display property and give it a value of none :
#myBtn {
display: none; /* Hidden by default */
}
And Position Fix to make it sticky on the right bottom :
#myBtn {
display: none; /* Hidden by default */
position: fixed; /* Fixed/sticky position */
}
then do some general styling for the button :
#myBtn {
display: none; /* Hidden by default */
position: fixed; /* Fixed/sticky position */
bottom: 20px; /* Place the button at the bottom of the page */
right: 30px; /* Place the button 30px from the right */
z-index: 99; /* Make sure it does not overlap */
border: none; /* Remove borders */
outline: none; /* Remove outline */
background-color: red; /* Set a background color */
color: white; /* Text color */
cursor: pointer; /* Add a mouse pointer on hover */
padding: 15px; /* Some padding */
border-radius: 10px; /* Rounded corners */
font-size: 18px; /* Increase font size */
}
#myBtn:hover {
background-color: #555; /* Add a dark-grey background on hover */
}
Step 3: Create the Scroll to top JS Function
First Select the button using javascript get element by id method :
mybutton = document.getElementById("myBtn");
then create a function that shows the button When the user scrolls down 100px from the top of the document :
window.onscroll = function() {scrollFunction()};
function scrollFunction() { if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
We need to create another function when the user clicks on the button, scroll to the top of the document :
function topFunction() {
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
In order to make the scroll smooth, we need to change the scroll behavior property in CSS, we can do that by adding scroll-behavior: smooth; in the CSS style of the HTML :
html {
scroll-behavior: smooth;
}