Scroll to top in vanilla JavaScript Vanilla JS
You can make an <a>
(anchor) scroll to the top of a page by setting the href
attribute to "#". This will add a # to the url. With JavaScript, you can scroll to the top of a page without adding a "#" to the url and make it a smooth scroll rather than instant.
This is how to instantly scroll to the top of a page in vanilla JavaScript.
toTop.addEventListener('click', function(e) {
e.preventDefault();
window.scroll(0,0);
});
The "#top" selects the element with an id of "top".
When using an <a>
(anchor) element for purposes like this instead of standard links, you can leave the href
value as '#'. The e.preventDefault()
stops an anchor from sending the user to its href url when it is clicked and in this case, stops the "#" from being added to the url.
This is how to smoothly scroll to the top of a page in vanilla JavaScript.
toTop.addEventListener('click', function(e) {
e.preventDefault();
window.scroll({ top: 0, left: 0, behavior: 'smooth' });
});
This smooth scrolling works in Chrome, Firefox & Opera natively. Use a polyfill for other browsers: http://iamdustan.com/smoothscroll/
Polyfills implement features in browsers that do not yet support them. They could technically be viewed as dependencies but the difference is that instead of writing in the syntax of a dependency, you are writing code that will likely be adopted by most browsers natively in future, so instead of having to re-write your code in future, you can simply remove the polyfill once more browsers adopt that feature. Polyfills also often have minimal overhead as they are used to enable specific features only rather than adding a vast array of additional features.
If you want to make a link scroll to a specific element on the page when clicked, read Scroll to element in vanilla JavaScript.
Thanks for reading.
Ryan
Published on 22 Mar 2019 (on a previous domain)
Last modified on 3 Jun 2021