JavaScript Window scrollTo() Tutorial

In this section, we will learn what the window scrollTo() method is and how to use it in JavaScript.

JavaScript Window scrollTo() Method

The document of a webpage is usually larger than the browser window. For this reason, in browsers we use scroll to move around a document.

The `scrollTo()` function is used to programmatically scroll a page by a certain amount.

Window scrollTo() Method Syntax:

window.scrollTo(xpos, ypos)

Window scrollTo() Method Parameter:

The function takes two arguments:

  • The first argument specifies how far horizontally the page should scroll. The value is in CSS pixel. For example, the value 500 means 500 pixels horizontally.
  • The second argument declares how far vertically the page should scroll. Again, this value is also based on CSS pixel. For example, the value 600 means 600 pixels vertically.

JavaScript Smooth Scroll

The `scrollTo()` method also takes an object that is called `ScrolltoOptions`, which in addition to holding the offset values, it can instruct the browser to smooth the scroll via the `behavior` property.

This object has 3 properties:

  • `top`: the value of this property specifies the vertical scrolling.
  • `left`: the value of this property declares the horizontal scrolling.
  • `behavior`: Via this property, we can create a smooth transition animation when scrolling occurs.

The values for the `behavior` property are:

  • `smooth`: The scrolling happens in a smooth way.
  • `auto`: The scrolling happens in a single move.

Window scrollTo() Method Return Value:

There’s no return value for this method.

Example: using Window scrollTo() method in JavaScript

See the Pen using Window scrollTo() method in JavaScript by Omid Dehghan (@odchan1) on CodePen.

Example: JavaScript smooth scroll

See the Pen JavaScript smooth scroll by Omid Dehghan (@odchan1) on CodePen.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies