Scroll to the Position of the Specified Element with JavaScript scrollIntoView

Contents
In this article, I will introduce 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.
auto | Initial value. |
---|---|
instant | Scrolls to the specified element position without animation. |
smooth | Scrolls to the position of the specified element with a smooth animation. |
block
The block property specifies the vertical scroll position.
start | Scroll so that the specified element appears at the top of the window. |
---|---|
center | Scroll so that the specified element is centered with respect to the vertical direction of the window. |
end | Scroll so that the specified element appears at the bottom of the window. |
nearest | Initial value. Calculates from the current display position and scrolls closer to the top or bottom. |
inline
The inline property specifies the horizontal scroll position.
start | Scroll so that the specified element appears on the left edge of the window. |
---|---|
center | Scroll so that the specified element is centered with respect to the horizontal direction of the window. |
end | Scroll so that the specified element appears at the right edge of the window. |
nearest | Initial value. Calculate from the current display position and scroll to the far left or near the right edge. |