Vanilla JavaScript Scroll to Top

— 3 minute read

Let's create a JavaScript powered scroll to top function. We will create a button that will sit at the right bottom of the page, and once we click it, it will take us to the top of the page.

Also view my article about a plain HTML scroll to top

HTML Structure permalink

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

That is all we are going to need, we will define some CSS and build the scrollToTop function in JavaScript.

CSS Setup permalink

.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 with the bottom and right, we offset it to the right bottom. We then do some general styling to make it look like a box.

JavaScript Scroll to Top permalink

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

It's good to note there are many ways of doing this. We can use the scrollIntoView like this article. But today, we are using the plain scroll function.

We can define the position we need to scroll to and the behavior.

Another way of doing the scroll can be with scrollTo:

window.scrollTo(0, 0);

See it in action on Codepen.

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

Browser Support permalink

Unfortunately, the scroll API is not fully supported!

Scroll to support

Thank you for reading, and let's connect! permalink

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