Scroll to the Position of the Specified Element with JavaScript scrollIntoView

12/30/2021

Contents

In this article, you will learn how to scroll to the position of the specified element with JavaScript scrollIntoView.

What is scrollIntoView?

The scrollIntoView is a method of Element that scrolls to the position of the specified element.

let element = document.getElementById('elem');

element.scrollIntoView();

You can also enter a Boolean value to specify whether the element scrolls to the top or bottom.

let element = document.getElementById('elem');

//Scroll to the top of the window
element.scrollIntoView(true);

//Scroll to the bottom of the window
element.scrollIntoView(true);

Some browsers allow you to specify advanced options as shown below.

let element = document.getElementById('elem');

element.scrollIntoView({
  behavior: "value",
  block: "value",
  inline: "value"
});

The scrollIntoView options

The scrollIntoView options consist of:

  • behavior (scrolling behavior)
  • block (vertical scroll position)
  • inline (horizontal scroll position)

By setting these options, you can fine-tune the scroll position.

behavior

The behavior property allows you to specify the behavior when scrolling.
It seems that scroll time and movement cannot be specified at present.

autoInitial value.
instantScrolls to the specified element position without animation.
smoothScrolls to the position of the specified element with a smooth animation.

block

The block property specifies the vertical scroll position.

startScroll so that the specified element appears at the top of the window.
centerScroll so that the specified element is centered with respect to the vertical direction of the window.
endScroll so that the specified element appears at the bottom of the window.
nearestInitial value.
Calculates from the current display position and scrolls closer to the top or bottom.

inline

The inline property specifies the horizontal scroll position.

startScroll so that the specified element appears on the left edge of the window.
centerScroll so that the specified element is centered with respect to the horizontal direction of the window.
endScroll so that the specified element appears at the right edge of the window.
nearestInitial value.
Calculate from the current display position and scroll to the far left or near the right edge.