How to Scroll to Top in JavaScript

Harshit Jindal Feb 02, 2024
  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
How to Scroll to Top in JavaScript

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);
Harshit Jindal avatar Harshit Jindal avatar

Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.

LinkedIn