How to use window.scrollTo in HTML

Overview

Have you ever clicked a button on a web application that automatically takes you to the top page?

In this shot, we will look at how to implement a scroll to the top button of a webpage easily and smoothly using the JavaScript window.scrollTo() method.

What is window.scrollTo()?

window.scrollTo() is a window object method that scrolls to a particular set of coordinates in a web page or document.

Syntax


window.scrollTo(x-axis, y-axiz)
 // OR
window.scrollTo(options)

The x-axis and y-axis here represent the horizontal and vertical coordinate values of the document.

See the example below.


window.scrollTo(0, 500);

The code above will cause the document to scroll 0px away from its x-axis (horizontal direction) and 500px from its y-axis (vertical direction).

options in the syntax above is an object that has values for which to scroll and the behavior when it scrolls.

See the example below.


window.scrollTo({
 top: 20,
 left: 20,
 behavior: "instant"
})

Parameters

The parameters it takes when you only pass the x-axis and y-axis are a set of numbers that represent the number of pixels away it should be from the 0 axis of x and y.

See the example of the first syntax above.

With the options, we can have properties such as the top and left or just one together with the behavior property.

It is the behavior property that we can use to implement a smooth scroll.

Code

Let’s take a look at how to scroll to the top page of a web page using window.scrollTo() with the options parameter.

Explanation

The smooth scroll above was implemented using the JavaScript code below.

document.getElementById("scroll").addEventListener("click", () => {
window.scrollTo({
top: 0,
behavior: "smooth",
});
});

With behavior property set to smooth and top set to 0, we were able to implement a smooth scroll to the top page.

Free Resources