Multiple ways to implement "Scroll to top"
17 Jun 2023 · Last updated: 19 Jun 2023 ·
Posted in weblog#tech
Tags: javascript, html
There are two primary ways to implement a "Scroll to top" button on webpages that I know of:
Using a link tag
Used by websites like Wikipedia and React docs, this solution is perhaps the simplest, as it doesn't require any JavaScript. Just link to "#" from a link tag in the HTML and all modern browsers will navigate the user to the top of the current page, much like what pressing Home does.
This solution does have a downside though. If you want to add smooth scrolling, you have to enable it in your global CSS which may not always be desirable.
<a href="#">Back to top</a>
Using window.scrollTo()
This JavaScript method has more flexibility. You can add a click event listener on a button and call window.scrollTo. Set the behaviour option to smooth to enable smooth scrolling or auto for instant navigation:
const scrollTopBtn = document.querySelector('#scroll-to-top')
scrollTopBtn.addEventListener('click', () => {
window.scrollTo(
top: 0,
behaviour: 'smooth',
)
})