#AD Top Online Web Development & Programming Courses | Udemy
Newsletter Screenshot

How to create a scroll to top button with JavaScript

Last modified May 23rd 2022 | GitHub Source Code [GitHub] | #js

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");
scrollTop();Code language: JavaScript (javascript)
  1. Create a const variable named scrollBtn with a HTML button element.
  2. Set the text of the button element to ↑ which is an up arrow HTML entity.
  3. Give the button an ID of scroll-btn so we can target with CSS.
  4. 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);
    }, 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.

Related Posts

#AD Shop Web Developer T-Shirts