Scroll to top buttons allow users to quickly return to the top of a webpage with a single click.
In this tutorial we’ll be creating a button that appears only after scrolling a certain distance down the page.
Let’s start by creating a scrollTop function that will contain all the required JavaScript:
const scrollTop = function () {
// all JavaScript will go here
};
scrollTop();
Next inside the scrollTop
function we’ll generate a HTML button element:
const scrollBtn = document.createElement("button");
scrollBtn.innerHTML = "↑";
scrollBtn.setAttribute("id", "scroll-btn");
document.body.appendChild(scrollBtn);
- Create a const variable named
scrollBtn
with a HTML button element. - Set the text of the button element to
↑
which is an up arrow HTML entity. - Give the button an ID of
scroll-btn
so we can target with CSS. - Insert the
scrollBtn
into the HTML.
Following the previous code add a scrollBtnDisplay
function and event listener:
const scrollBtnDisplay = function () {
window.scrollY > window.innerHeight
? scrollBtn.classList.add("show")
: scrollBtn.classList.remove("show");
};
window.addEventListener("scroll", scrollBtnDisplay);
This toggles a show class when the user has scrolled further down the page than the height of the window.
Finally let’s add the functionality for when a user clicks the button inside the scrollTop
function:
const scrollWindow = function () {
if (window.scrollY != 0) {
setTimeout(function () {
window.scrollTo(0, window.scrollY - 50);
scrollWindow();
}, 10);
}
};
scrollBtn.addEventListener("click", scrollWindow);
Smooth scrolling could be done using CSS scroll-behavior:smooth;
but this isn’t yet supported in Safari.
So instead we use a setTimeout
that scrolls -50px every 10 milliseconds until the top of the page is reached.
Finally here’s some CSS to create a rounded button that fades in/out when the show
class is toggled:
#scroll-btn {
opacity: 0;
width: 40px;
height: 40px;
color: #fff;
background-color: #ef476f;
position: fixed;
bottom: 10%;
right: 10%;
border: 2px solid #fff;
border-radius: 50%;
font: bold 20px monospace;
transition: opacity 0.5s, transform 0.5s;
}
#scroll-btn.show {
opacity: 1;
transition: opacity 1s, transform 1s;
}
You now have a fully functioning scroll-to-top button to use in you next web project.
Top comments (1)
The most minimalist
scroll-to-top
.