JavaScript

JavaScript | Window scrollTo() Method

The window scrollTo method is used to scroll the browser window to a specific coordinate. This method is named the scrollTo() while the window is the Window Object. A browser window that is open is represented by the window object. To better understand this method, quickly go over the syntax given below:

Syntax of the scrollTo() Method

window.scrollTo(X-coordinate, Y-coordinate);

In this syntax:

  • window is the browser’s window Object.
  • X-coordinate is the horizontal displacement to the browser’s window at.
  • Y-coordinate is the vertical displacement to pan the browser’s window at.

Demonstration of the Window scrollTo() Method

To demonstrate the working of the scrollTo method, start by creating an HTML file with the following lines:

<center>
      <b class="scrolled">I am Placed at 4000px Vertically</b>
      <button onclick="clicked()">Click me to scroll down</button>
</center>

In this above HTML code snippet,

  • A bold tag was created with some text inside it with the class being scrolled. This class will be used to place this tag at 4000px with the help of CSS.
  • A button was created which calls the clicked() function in the JavaScript file.

After that is done, we want to add the following lines to the CSS of our webpage:

body {
  height: 7000px;
}
.scrolled {
  position: absolute;
  top: 4000px;
}

In the above CSS snippet:

  • The height of the body tag is set to 7000px so the webpage becomes scrollable even without having more elements on it.
  • The bold tag with the class scrolled has been placed at 4000px.

Executing the webpage now provides us the following output on the browser’s window:

As you can see from the output, to visit the bold tag, one must manually scroll the browser’s window.

To add functionality to the button so that it scrolls us directly on the bold tag with text, write the following lines in the script file:

function clicked() {
  window.scrollTo(0, 4000);
}

In these lines, the function clicked() is created, which is called upon pressing the button, and in this function, we are simply passing the Y-coordinate as 4000px to the window scrollTo() method. This provides the following outcome on the HTML webpage:

As it is clearly shown in the output, pressing the button pans the browser’s window to 4000px vertically.

Wrap up

The window scrollTo() method is used to call the browser’s window object and then pan the browser’s window to a specific position by passing in the x and y coordinates in its arguments. This article demonstrated the working of the window scrollTo() method with the help of an example.

About the author

Abdul Mannan

I am curious about technology and writing and exploring it is my passion. I am interested in learning new skills and improving my knowledge and I hold a bachelor's degree in computer science.