Fixing scrollIntoView in Selenium using JavascriptExecutor

To scroll to a specific element in selenium, we use scrollIntoView method.

Lets’ understand the scrollIntoView method very quickly.

scrollIntoView:

The Element interface's scrollIntoView() method scrolls the element's parent container such that the element on which scrollIntoView() is called is visible to the user

Ref: https://developer.mozilla.org/en/docs/Web/API/Element/scrollIntoView

Now let’s take an example to understand it properly:

Let’s assume we want to scroll to the third search result in google search.

We will use the below code:

JavascriptExecutor jse =(JavascriptExecutor)driver;
jse.executeScript("arguments[0].scrollIntoView();", element);

Output:

The Problem statement:

This scrolls the element into view but it goes behind the header on the page (as mentioned on the above screenshot). And we will not able to view the heading of our desired search result page.

Now, How can we scroll element into view so that the element is right below the header instead of behind the header?

How to solve the problem?

To solve this we can use the below approaches:

  1. We could scroll it at the bottom instead:
WebElement element = driver.findElement(By.id("")); 
JavascriptExecutor jse =(JavascriptExecutor)driver;
jse.executeScript("arguments[0].scrollIntoView(false);", element);

Output:

2. We could also scroll it at the top and then by a 1/4th of the height of the view:

WebElement element = driver.findElement(By.id("")); 
JavascriptExecutor jse =(JavascriptExecutor)driver;
jse.executeScript("arguments[0].scrollIntoView(true); window.scrollBy(0, -window.innerHeight / 4);", element);

Output: You can see a clear view in this example.

3. Or We can also scroll it just below our fixed header:

WebElement element = driver.findElement(By.id("")); 
WebElement header = driver.findElement(By.id(""));
JavascriptExecutor jse =(JavascriptExecutor)driver;
jse.executeScript("arguments[0].scrollIntoView(true); window.scrollBy(0, -arguments[1].offsetHeight);", element, header);

Output:

Geek Culture

Proud to geek out. Follow to join our +1.5M monthly readers.