JavaScript Window scrollBy() Tutorial

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

JavaScript Window scrollBy() Method

The `scrollBy()` function serves the same purpose as the `scrollTo()`. Basically, we use the function to programatically scroll a document to a certain location.

The difference, however, is that:

  • The `scrollTo()` function scrolls to the target location without considering the current location in the document.
  • The `scrollBy()` scrolls related to the current location in the document.

For example, if horizontally and vertically, we’re at the `(20, 40)` position in the document. If we apply the `scrollBy(100, 100)`, the final location will be `(120, 140)`. As you can see, the new values are added to the old location.

Window scrollBy() Method Syntax:

window.scrollBy(xnum, ynum)

Window scrollBy() 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.

The `scrollBy()` 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 scrollBy() Method Return Value:

There’s no return value for this method.

Example: JavaScript set scroll position

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

Leave a Reply