It is important for every website to put scroll to top button on website. And mostly for blog and news sites, it is the most mandatory thing. It helps the visitors to directly go back to top of the page without scrolling up.
Table of Contents
Create a Scroll To Top Button
In this tutorial, we will be using HTML, CSS and JavaScript to make amazing Scroll to to Button. We are using JavaScript so that we could hide the button when the page is not scrolled.
Step 1 : Add HTML
<div id="topBtn">
<i class="fas fa-chevron-up"></i>
</div>
Here, I’m using Font Awesome font, so you need to add Font Awesome CDN. Kindly copy,
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet">
And paste it into head section.
Also Read : How To Create a Scroll Indicator
Step 2 : Add CSS
html {
scroll-behavior: smooth;
}
#topBtn {
position: fixed;
right: 18px;
bottom: 14px;
display: none;
justify-content: center;
align-items: center;
background: #cc4551;
color: #fff;
width: 42px;
height: 42px;
cursor: pointer;
}
The topBtn container is fixed to the bottom right corner and initially we used display : none property. It will get displayed once user scroll down using JavaScript down below.
Step 3 : Add JavaScript
var topBtn = document.getElementById("topBtn");
window.onscroll = function() {
//When we scroll, then scrollFunction will get called
scrollFunction()
};
function scrollFunction() {
// Results in scroll
var currentScrollPos = window.pageYOffset;
prevScrollpos = currentScrollPos;
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
topBtn.style.display = "flex";
} else {
topBtn.style.display = "none";
}
}
// When we click in topBtn, then topFunction will get called
topBtn.addEventListener("click", topFunction);
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
When window get scrolled, scrollFunction get called. And in scrollFunction, when user scroll 20px or more to down, the button get displayed, it is because we used display : flex property. And in remaining condition, that is else condition, the button will get display = none property.
And we used event listener in topBtn, when topBtn get clicked, then topFunction function will get called. And now, it will scroll the page automatically to the top.
The Sum Up
We used JavaScript here so that we can find either the page is scrolled or not. The condition is simple, if the page get scrolled, then only we have to display the button. In remaining condition that is else condition, the button will be hidden.