Vanilla JavaScript Scroll to Top
permalinkIn 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 right bottom 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 permalink
<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 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 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 permalink
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 permalink
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!
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