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.
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 scrollToTop 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 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
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
Unfortunately, the scroll API is not fully supported!
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
Top comments (11)
Easier method with no JS:
Add this right after the opening body tag:
For the scroll to top button use the code
No need to make the target tag an anchor, a hidden div is enough
Also add:
To make it smooth
The smooth behaviour is a welcome addition, I've wrote an article about this method as well: daily-dev-tips.com/posts/plain-htm...
A Codepen will help a lot!
Hey Mubashir, In this article you will find a Codepen. daily-dev-tips.com/posts/plain-htm...
Thank you for the post... It was helpful
Thanks man, glad it helped! 🤟
it's not work in hash spa mode (like site.com/#read/35)
Hey Zen, I do indeed think the Hash needs to be in the end for the browser to understand
Hey Easrng, I've wrote an article about this function as well today: daily-dev-tips.com/posts/plain-htm...
Yes, aware of this, super solution as well.
I will do another article about this way. There are just so many ways of doing the same thing really :D