← coderrocketfuel.com

Programmatically Scroll to the Top of a Web Page Using JavaScript

How can you scroll to the top of a web page using only pure JavaScript? And do so without using JQuery or any other external libraries/tools/etc.

You can do that with this method:

window.scrollTo(0, 0);

That will scroll the page all the way to the top.

Both parameters to the scrollTo() method are x and y coordinates like this: scrollTo(x-coord, y-coord).

You can also specify if the page should scroll with or without a smooth transition:

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

This would scroll the page to the top with a smooth animation.

behavior: "instant" would scroll to the top instantly with no animation.

If the behavior option is not set, scrollTo() will use whatever is set for the scroll-behavior CSS property.

Thanks for reading and happy coding!