Here, in this section, we will learn how we can use the scrollIntoView () method for scrolling the elements into the view. We will also implement an example through which we can understand the working and use of the function.
The scrollIntoView () method is used for scrolling the elements on the viewport.
In the above-described syntaxes, the specified parameters are:
- alignToTop: The parameter alignToTop contains the Boolean value that can be either true or false, and by default, its value is set to true. For a particular code, if this parameter finds it true, as a result, the top of the element gets aligned either to the top of the visible area or to the top of the viewport area. However, in case the value is set to false; as a result, the bottom of the element gets aligned either to the bottom of the viewport or to the bottom of the visible area of the scroll bar.
- options: It is an object-type argument, and the browser support may vary. This parameter provides more control for the alignment of the element in the view.
It has the following properties:
- The first property is the behavior that defines the transition animation. The property can have any of the two values, i.e., auto or smooth, where the default value is auto.
- The block property is another which defines the vertical alignment of the elements and can have any of the four value, i.e., start, center, end or nearest. Here, the default value is start.
- The last property is the inline property which defines the horizontal alignment and can have any of the four values, i.e., start, center, end, or nearest. Here, the default value is nearest.
Now, let's take an example of the scrollIntoView () method.
Test it Now
On clicking the button once, we got the following output:
In the output, you can see that we are not able to see the list items in the viewport without scrolling. We are able to see these list items only after pressing the button where on the button click, the list item gets scrolled into the visible area.
- We have created a list of items, and in between the items, we have created an id =id_test so that we can get our scrolling point from where the window will get scrolled.
- Next, we have created a button 'Click it' on which we have invoked the function when the user makes a click.
- As the function is the JS function, so as per the function definition, the particular list of items will be fetched, and it will be stored in the specified variable.
- When we use the scrolIntoView property, the windows get scrolled to the particular list item.
- Finally, the item will be visible in the viewport.