How to scroll a Web Page using coordinates of WebElement in Selenium WebDriver ?

Every webElement on WebPage has its own unique position in form of X & Y coordinates.

You may have seen that some Web Elements are at the bottom of page which are not visible until you scroll the page down.

In some case while doing automation, we have to scroll to the Web Element in order to perform actions on it. And we can actually achieve that by using the coordinates of web element.

First, we have to find the X & Y coordinates of Web element by using following code :

WebElement element = driver.findElement(By.xpath(""));
Point point = element.getLocation();
int x_coordinate = point.getX();
int y_coordinate = point.getY();

We have to import a following package to access Point class : import org.openqa.selenium.Point

And for Scrolling, we will be using the following code :

JavascriptExecutor javScriptExecutor = (JavascriptExecutor) driver;
javScriptExecutor.executeScript("window.scrollBy(" + x_coordinate + ", " + y_coordinate + ");");

Scenario for Sample Script

1. Open
2. Scroll to “Post Comment” button displayed at the bottom of page.
3. Close browser.

Script to automate above scenario

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class ScrollTest {

	WebDriver driver;

	public void setUp() {
		System.setProperty("", "C:\\gridsetup\\chromedriver.exe");
		driver = new ChromeDriver();

	public void test01() throws InterruptedException {
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
		WebElement postCommentButton = driver.findElement(By.xpath("//input[@name='submit']"));
		Point point = postCommentButton.getLocation();
		int x_coordinate = point.getX();
		int y_coordinate = point.getY();
		scrollToElement(x_coordinate, y_coordinate);

	public void scrollToElement(int x, int y) {
		JavascriptExecutor javScriptExecutor = (JavascriptExecutor) driver;
		javScriptExecutor.executeScript("window.scrollBy(" + x + ", " + y + ");");



If you really like the information provided above, please don’t forget to like us on Facebook, you can also leave the comment.

Leave a Reply

Your email address will not be published. Required fields are marked *