Scroll to an element with Selenium WebDriver

We need to take into account that a web element, for instance a button, can dynamically go out of view depending on the screen resolution we test with. So how do we wait for an element that we want to click on and if we cannot find it, scroll to it and try again? We’ll use two methods that work for any web element.

  1. A scrollToElement method that gets the web element into view.
  2. A waitAndClick method that uses the scrollToElement method.

To make things more realistic we include waiting for a loading indicator to disappear before checking whether we can click on an element. The assumption is that the class containing our methods has an instance of WebDriver called driver.

We’ll use the JavascriptExecutor in scrollToElement.

private void scrollToElement(WebElement el) {
    if (driver instanceof JavascriptExecutor) {
        ((JavascriptExecutor) driver)
            .executeScript("arguments[0].scrollIntoView(true);", el);
    }
}

Now we can finish the job in waitAndClick.

public void waitAndClick(WebElement el) {
    try {
        WebDriverWait wait = new WebDriverWait(driver, 5, 200);
        wait.until(ExpectedConditions.invisibilityOfElementLocated(By.className("loader")));
        wait.until(ExpectedConditions.elementToBeClickable(el)).click();
    catch (WebDriverException wde) {
        scrollToElement(el);
        el.click();
    }
}

This method tries to click on the element. If it fails, it scrolls to the element and tries to click again. That’s it!

Author: David Baak

To code or not to code? That's true.

2 thoughts on “Scroll to an element with Selenium WebDriver”

    1. Yes, that would be like this:
      driver.execute_script(“arguments[0].scrollIntoView(true);”, el)
      Where el is the web element you want to scroll to.

Leave a Reply

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