#AD Top Online Web Development & Programming Courses | Udemy

How to create a scroll to top button with JavaScript

Last modified October 15th 2021 | #js | GitHub Source Code [GitHub]

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();
Code language: JavaScript (javascript)

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);
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); 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.

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; }
Code language: CSS (css)

You now have a fully functioning scroll-to-top button to use in you next web project.

Related Posts

#AD Shop Web Developer T-Shirts