scrollIntoView
Suppose you have a list of elements and you want a specific element to be highlighted and scrolled into view.
To achieve this, you can use the element.scrollIntoView()
method. The element.scrollIntoView()
accepts a boolean value or an object:
or
The method accepts one of the following two arguments:
alignToTop
alignToTop
The alignToTop
is a boolean value.
If it is set to true
, the method will align the top of the element to the top of the viewport or the top of the visible area of the scrollable ancestor.
If the alignToTop
is set to false
, the method will align the bottom of the element to the bottom of the viewport or the bottom of the visible area of the scrollable ancestor.
By default, the alignToTop
is true
.
options
options
The options
argument is an object that gives more control over of alignment of the element in the view. However, the web browser support may be slightly different.
The options
object has the following properties:
behavior
property defines the transition animation. Thebehavior
property accepts two values:auto
orsmooth
. It defaults toauto
.block
property defines the vertical alignment. It accepts one of four values:start
,center
,end
ornearest
. By default, it isstart
.inline
property defines horizontal alignment. It also accepts one of four values:start
,center
,end
ornearest
. It defaults tonearest
.
JavaScript scrollIntoView() Example
Suppose that you have an HTML page with a list of the programming language as follows:
Without scrolling, the JavaScript
list item, which has a class called special
, is not in the viewport. When the button "Scroll Into View"
is clicked, the JavaScript
list item is scrolled into the view:
How it works:
First, select the button with the
btn
class and list item with thespecial
class.Then, attach an event listener to the click event of the button.
Finally, scroll the
JavaScript
list item into the viewport by calling theel.scrollIntoView(true)
method in the click event handler.
Here is the JavaScript scrollIntoView() demo.
To align the JavaScript
list item to the bottom of the view, you pass false
value to the scrollIntoView()
method:
In this tutorial, you have learned how to use the JavaScript scrollIntoView()
method to scroll an element into the viewport.
Last updated