In this tutorial we’ll be creating a scroll to top button with JavaScript. These buttons allow users to quickly return to the top of the page when clicked making them especially useful when using mobile devices with long pages of content.
Let’s start by creating a scrollTop
function that will contain all the required JavaScript:
const scrollTop = function () {
// all JavaScript will go here
};
scrollTop();
Code language: JavaScript (javascript)
Next inside the scrollTop
function we’ll generate a HTML button element:
const scrollTop = function () {
const scrollBtn = document.createElement("button");
scrollBtn.innerHTML = "↑";
scrollBtn.setAttribute("id", "scroll-btn");
document.body.appendChild(scrollBtn);
};
scrollTop();
Code language: JavaScript (javascript)
- Create a
const
variable namedscrollBtn
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);
Code language: JavaScript (javascript)
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);
Code language: JavaScript (javascript)
Smooth scrolling could be done using CSS scroll-behavior:smooth;
but this isn’t yet supported in Safari. Instead we’ve used 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;
}
Code language: CSS (css)
You should now have a fully functioning scroll-to-top button to use in you next web project. A full working example of this code used in this tutorial can be found on GitHub. Enjoy and thanks for reading.