Subscribe

Vanilla JavaScript Scroll to Top

✍️

Guide to learn how to smoothtly scroll back to the top of the page in Vanilla JavaScript. See the example in Codepen!

13 Jun, 2020 · 2 min read

In today’s tutorial, we will learn how to scroll to the top of a page in Vanilla JavaScript.

So let’s code a JavaScript powered scroll to top function.

We will create a button that will sit at the bottom right of the page. Once we click it, it will take us back to the top of the page with a smooth scroll.

Also view my article about a plain HTML scroll to top

HTML Structure

<button onclick="scrollToTop()" class="scroll-top">☝️</button>

That is all we are going to need. We will define some CSS and build the scroll to top function in JavaScript.

CSS Setup

.scroll-top {
  position: fixed;
  bottom: 25px;
  right: 25px;
  z-index: 99;
  outline: none;
  background-color: #efefef;
  border: 1px solid #333;
  cursor: pointer;
  padding: 15px;
  border-radius: 4px;
}

The scroll button gets a position: fixed, and we offset it to the right bottom with the bottom and right. We then do some general styling to make it look like a box.

Vanilla JS Scroll to Top

It’s good to note there are many ways of scrolling the browser window to the top. We can also use the scrollIntoView function, as shown in this article.

But today, we are using the plain JavaScript scroll function.

This is our scrollToTop JavaScript function. We can define the position we need to scroll to and the behavior.

function scrollToTop() {
  window.scroll({ top: 0, left: 0, behavior: 'smooth' });
}

Another way of doing the scroll can be with scrollTo:

window.scrollTo(0, 0);

See the code examples in this Codepen

See the Pen Vanilla JavaScript Scroll to Top by Chris Bongers (@rebelchris) on CodePen.

Browser Support

Unfortunately, the scroll API is not fully supported!

Scroll to top browser support

Thank you for reading, and let’s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2099 devs and subscribe to my newsletter