Scroll element to the middle of the screen with Selenium


We can scroll to the middle of the screen with Selenium webdriver using the JavaScript Executor. Selenium can execute JavaScript commands with the help of the executeScript method.

To scroll to the middle of the screen, we have to first identify the element upto which we want to scroll on the page. Then pass scrollIntoView and the web element as parameters to the executeScript method.

JavaScript command scrollIntoView can have multiple optional parameters. They are −

  • behavior – This can have the values - smooth or auto. It describes the animation of the transition. The default value is auto.

  • block – This can have the values - start, end, center, or nearest. It describes the vertical alignment. The default value is start.

  • inline – This can have the values - start, end, center, or nearest. It describes the horizontal alignment. The default value is nearest.

Syntax

WebElement e = driver.findElement(By.name("txt"));
JavascriptExecutor j = (JavascriptExecutor)driver;
j.executeScript ("arguments[0].scrollIntoView({block: 'center', inline: 'nearest'})", e);

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollToMiddle{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/index.htm");
      //identify element
      WebElement m = driver.findElement(By.linkText("Latest Courses"));
      //scroll to middle with Javascript Executor
      JavascriptExecutor j = (JavascriptExecutor) driver;
      j.executeScript("arguments[0].scrollIntoView({block: 'center', inline: 'nearest'})", m);
      System.out.println("Text is: " + m.getText());
   }
}

Output

Updated on: 06-Apr-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements