JavaScript Scroll to Top

  1. Use the window.scrollTo() Function to Scroll to the Top of the Page
  2. Use the Anchor Tag to Scroll to the Top of the Page
  3. Use jQuery’s scrollTo() Function to Scroll to the Top of the Page

This tutorial teaches how to scroll to the top of the page using JavaScript.

Use the window.scrollTo() Function to Scroll to the Top of the Page

The scrollTo() method of the window is used to scroll to a specific location on a page. It takes two arguments: the x and y coordinate of the point to which we want to scroll. We can pass x and y as 0 to scroll to the top of the page.

window.scrollTo(x-coordinate, y-coordinate)

Use the Anchor Tag to Scroll to the Top of the Page

The anchor tag takes the reference of the page to open when the link is clicked. If we pass # as the value of the href attribute, it will scroll to the top of the page.

<a href="#"> Top of Page </a>

Use jQuery’s scrollTo() Function to Scroll to the Top of the Page

The scrollTo() function helps us to get/manipulate the vertical scrollbar position of an HTML element. It takes one argument, the position to scrollTo(). We can use this function to reach the top of the page by applying it on the window property and setting the position parameter as 0.

$(window).scrollTop(0);
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.