We can use JavaScript to scroll to the top of the page by using the scrollTo method along with the top and behavior properties.

window.scrollTo({ top: 0, behavior: 'smooth' });

Let’s say I have the following HTML:


To scroll to the top of the page, we can use the scrollTo() method and pass it the top and behavior properties. We set the top property to 0 so that it scrolls to the top of the page, and behavior to “smooth” to get a smooth scroll to the top.

Here is the JavaScript code:

window.scrollTo({ top: 0, behavior: 'smooth' });

Note that we can also do this with jQuery using the animate method.

Using JavaScript to Scroll to the Top of the Page With a Click

Let’s say we have the following HTML code and we want to scroll smoothly to the top of the page.

Scroll Top

We can utilize both an onclick event method along with the Window scrollTo() method to scroll to the top of the page.

We add an onclick event to the button so that we can scroll to the top of the page when the user clicks a button.

Below is the JavaScript code which will allow the user to scroll to the top of the page:

function scrollToTop() {
  window.scrollTo({ top: 0, behavior: 'smooth' });
};

The final code and output for this example of how to scroll to the top of the page using JavaScript is below.

Code Output:

Scroll Top

Full Code:

Scroll Top

Hopefully this article has been useful for you to understand how to use JavaScript to scroll to the top of the page.

Categorized in:

JavaScript,

Last Update: March 13, 2024