How to Scroll to the Top of the Page Using JavaScript

To make the page jump on the top instantly can be done with the native JavaScript method, namely —window.scrollTo(x-coord, y-coord). This property of the window interface scrolls to a particular set of coordinates in the document. It has two parameters: the x and y.

  • x-coord - pixel along the horizontal axis.
  • y-coord - pixel along the vertical axis.
window.scrollTo(x-coordinate, y-coordinate)

Setting both parameters to 0 will scroll the page to the topmost and leftmost point.

function scrollToTop() {
  window.scrollTo(0, 0);
}
Example:
<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .scroll {
        height: 1200px;
        background-color: yellow;
      }
    </style>
  </head>
  <body>
    <h1>  Scroll </h1>
    <p class="scroll">This is a large scrollable area.</p>
    <button onclick="scrollToTop()">
      Click to scroll to top
    </button>
    <script>
      function scrollToTop() {
        window.scrollTo(0, 0);
      }
    </script>
  </body>
</html>

Window Interface

The Window interface represents a window that includes a DOM document.

It is the host of a variety of functions, objects, namespaces, and constructors that are not associated with the user interface window. The Window Interface is a place to include these items needed to be globally available.

The window global variable representing the window in which the script is running is exposed to JavaScript code.