How to scroll element to mid/center, top or bottom of the screen in Selenium?

We all come across scenarios where we need to interact with an element that is not in the visible area of the browser. That element may be in the. bottom of the page or top of the page if the page is already scrolled down. In general, WebDriver scrolls the element into view when we make a findElement() call. Sometimes it fails to do so. And sometimes it scrolls the element but some other element like a fixed navbar comes on top of that element. Hence the next operation to click() or sendKeys() also fails.

We can explicitly make an element scroll to mid, top or bottom of the screen in Selenium WebDriver. We need to use the JavaScriptExecutor to inject some JavaScript code in the browser to do this job. Please feel free to refer This Tutorial if you want to read about executing JavaScript in Selenium.

Three variants of JavaScript function scrollIntoView()

scrollIntoView()

It scroll the top of the element to the top of the screen.

scrollIntoView(alignToTop)

alignToTop is a boolean and the default value is true. If it is set to true, the top of the element will be aligned to the top of the visible area of the scrollable ancestor. If it is set to false, the bottom of the element will be aligned to the bottom of the visible area of the scrollable ancestor.

scrollIntoView(scrollIntoViewOptions)

scrollIntoViewOptions is an object with the following properties:

{
  "behaviour": "",
  "block": "",
  "inline": ""
}
  • behavior It is Optional. It defines the transition animation. It takes auto or smooth values. It defaults to auto
  • block It is optional. It defines vertical alignment. It takes startcenterend, or nearest. It defaults to start.
  • inline It is also optional It defines horizontal alignment. It takes startcenterend, or nearest. It defaults to nearest.

Scroll top of the element to the top of the screen

WebElement elem = driver.findElement(By.id("some-id"));
JavascriptExecutor js = (JavascriptExecutor)driver;
//Scroll to top
js.executeScript("arguments[0].scrollIntoView()", elem);

Scroll to bottom of the screen

WebElement elem = driver.findElement(By.id("some-id"));
JavascriptExecutor js = (JavascriptExecutor)driver;
//Scroll to bottom
js.executeScript("arguments[0].scrollIntoView(false)", elem);

Scroll to mid/center of the screen

WebElement elem = driver.findElement(By.id("some-id"));
JavascriptExecutor js = (JavascriptExecutor)driver;
//Scroll to bottom
js.executeScript("arguments[0].scrollIntoView({behavior: "smooth", block: "center", inline: "nearest"}))", elem);

References:

Leave a Reply