Scroll to Top in Vanilla JavaScript

Scroll to Top in Vanilla JavaScript

Introduction

Whenever you have a website that prompts users to scroll down a lengthy amount - offering a button to scroll back to the top is a nice gesture!

In this hands-on guide, we will learn how to make an animated HTML/CSS/JS button to scroll to the top in Vanilla JavaScript.

Note: The source code is available on GitHub.

Getting Started

We'll be creating the functionality from scratch and styling it. Using a querySelector(), we'll select the created button and toggle its visibility on and off based on where the user is on the page, and trigger an event to scroll to the top on each click.

If you'd like to read about creating a scroll-to-top in React, read our How to Scroll to Top in React with a Button Component!

Because the button is fixed to a certain location (bottom-right) using the CSS position attributes, the markup for this functionality may be inserted anywhere inside the body element of your HTML code:

<div className="scroll-to-top">
    <span class="btn btn-position btn-style">^</i>
</div>

Once added, we can style the button and its parent <div>. We'll fix the position of the button to the bottom right, offsetting it a little from the bottom and the right-hand side:

.scroll-to-top {
  position: relative;
}

.btn-position {
  position: fixed;
  bottom: 40px;
  right: 25px;
  z-index: 20;
}

.btn-style {
  background-color: #551b54;
  border: 2px solid #fff;
  border-radius: 50%;
  height: 50px;
  width: 50px;
  color: #fff;
  cursor: pointer;
  animation: movebtn 3s ease-in-out infinite;
  transition: all 0.5s ease-in-out;
  font-size: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  visibility: hidden;
}

We've set the visibility of this button to hidden by default, so that the button only appears when the user has scrolled down to a particular position(Y-axis) - we'll do this by altering its property with JavaScript later. Finally, let's add a hover and some animation to the button so it doesn't stand still:

.icon-style:hover {
  animation: none;
  background: #fff;
  color: #551b54;
  border: 2px solid #551b54;
}

@keyframes movebtn {
  0% {
    transform: translateY(0px);
  }
  25% {
    transform: translateY(20px);
  }
  50% {
    transform: translateY(0px);
  }
  75% {
    transform: translateY(-20px);
  }
  100% {
    transform: translateY(0px);
  }
}

Implementing the Logic

Now that the button is styled, and invisible - let's implement the logic that makes it visible once the user scrolls down. We'll select it via querySelector() and attach an EventListener to the element:

const scrollBtn = document.querySelector(".btn");

Now, based on the position of the window's Y value (how much the user has scrolled vertically, starting at 0) - we'll set the visibility of the element to "visible" or "hidden" if the Y value is below a certain threshold:

const btnVisibility = () => {
    if (window.scrollY > 400) {
        scrollBtn.style.visibility = "visible";
    } else {
        scrollBtn.style.visibility = "hidden";
    }
};

Now we have a function which, when called, checks whether the webpage has been scrolled down to 400, and sets the visibility of the button element to visible, else it sets it to hidden.

Finally - we'll want to repeatedly call this function to repeatedly check the position and adjust the visibility accordingly. This is best done through an event listener that triggers the function on each scrolling change:

document.addEventListener("scroll", () => {
    btnVisibility();
});

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

The last piece of code we'll want to attach to an event listener is the logic to scroll the user back up programmatically when they click a button. The scrollToTop() function of the window instance does just that! We can set what the "top" is, by providing a Y coordinate, and can call the method on each "click" event on the button:

scrollBtn.addEventListener("click", () => {
    window.scrollTo({
        top: 0,
        behavior: "smooth"
    });
});

Note: window.scrollTo() has a behavior parameter that indicates whether the scrolling should progress softly (smoothly) or instantly in a single step (auto the default value).

That's it! Try scrolling down the page - an animated button will appear. Once it does and you click it, you'll smoothly be taken back to the top of the page:

Conclusion

Scrolling to the top of the page isn't difficult - even with event listeners and animations! In this hands-on guide, we've learned how to implement the scroll-to-top functionality with Vanilla JavaScript and styled the button.

Last Updated: April 20th, 2022
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Joel OlawanleAuthor

Frontend Developer & Technical Writer

Go Unlimited

  • Access all of our courses and guided projects
  • Master new skills and advance your career
  • Comprehensive lessons and expert guidance
  • Early access to all new courses and content

Sign up today!

$19/mo

Getting Started with AWS in Node.js

Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

© 2013-2022 Stack Abuse. All rights reserved.

DisclosurePrivacyTerms