Skip to main content

Multiple ways to implement "Scroll to top"

Jun 17, 2023 · Last updated: Jun 19, 2023 ·
Posted in weblog#tech
Categories: javascript, html

There are two primary ways to implement a "Scroll to top" button on webpages that know of:

  1. 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>
  1. window.scrollTo

This JavaScript method has more flexibility. You can add a click event listener on a button and call window.scrollTo() to navigate to the top. There are many options, including one for enabling smooth scrolling:

const scrollTopBtn = document.querySelector('#scroll-to-top')

scrollTopBtn.addEventListener('click', () => {
  window.scrollTo(
    top: 0,
    behaviour: 'smooth'	,
  )
})