How to Use the JavaScript Window.scroll Function?

Estimated read time 1 min read

The Window.scroll method in JavaScript can be used to scroll the window to a specific position. The method has the following syntax:

window.scroll(x-coord, y-coord)

Where x-coord is the horizontal coordinate and y-coord is the vertical coordinate. The values are measured in pixels, and you can use negative values to scroll up and to the left.

Here’s an example that scrolls the window to the top left corner:

window.scroll(0, 0);

You can also use the scrollBy method to scroll by a certain amount of pixels, rather than to a specific coordinate:

window.scrollBy(x-amount, y-amount)

For example, the following code will scroll the window down by 100 pixels:

window.scrollBy(0, 100);

Note that these methods affect the scroll position of the entire window, not just a specific element. If you want to scroll an element within the page, you can use the scrollTop and scrollLeft properties. For example:

document.getElementById("element-id").scrollTop = 100;

This will set the scroll position of the element with the ID “element-id” to 100 pixels from the top.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply