Hello Folks,

In previous posts, we have seen scrolling a page by pixels using scroll, scrollTo or scrollBy methods. All these methods accept co-ordinates. These co-ordinates must be known in advance to scroll perfectly which is not possible all the times. If your script is running at different screen sizes, you can not use same co-ordinates for all screen sizes. You can create customized methods which will take co-ordinates based on screen size which is not feasible.

scrollIntoView() of Javascript:

Javascript provides an another useful method to scroll named scrollIntoView(). This method scrolls the element on which it’s called into the visible area of the browser window. It means, you no need to pass co-ordinates of elements if you use this method. You just locate element and call this method on located element. Javascript automatically scroll till the element is visible on browser’s visible area.

Syntax:

  1. element.scrollIntoView(); : In this method default value of alignToTop will be true.
  2. element.scrollIntoView(alignToTop);

alignToTop is a Boolean argument. If alignToTop is:

  • true: The top of the element will be aligned to the top of the visible area of the scroll-able ancestor.
  • false: The bottom of the element will be aligned to the bottom of the visible area of the scroll-able ancestor.

Note: The element may not be scrolled completely to the top or bottom depending on the layout of other elements. Suppose, you want to scroll to an element which is in down of the page with alignToTop as true. It will not scroll to match it top of the visible area of the scroll-able ancestor as page can not scrolled beyond its limit.

Java code example 1:

Output:

 

Java code example 2:

Output:

Java code example 3:

Output:

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappySelenium

Leave a Reply