What is the best way to scroll to a web element located on the current page within the viewport using Selenium

Viewed 1084

I am new to the automation and I would like to know how to scroll to a web element on the current page using selenium and java.

I have tries many methods which is described in stackoverflow. But couldn't able to solve my problem.

Solutions I tried:

WebElement element = driver.findElement(By.id("id_of_element"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500);
3 Answers

You can use Actions class provided by Selenium.

public void scrollToElement(WebElement element){
    Actions actions = new Actions(driver);
    actions.moveToElement(element);
    actions.perform();
    WebDriverWait wait = new WebDriverWait(driver, 60);
    wait.until(ExpectedConditions.visibilityOf(element));
}

Here I have added an explicit wait and it will wait until the web element is visible. Maximum waiting time will be 60 seconds. If the web element is not visible within 60 seconds, this will throw an exception. You can increase the waiting time by changing this line.

WebDriverWait wait = new WebDriverWait(driver, 60);

Hope this helps.

To scroll a WebElement on the current page within the Viewport using Selenium and Java you need to induce WebDriverWait for the visibility of element located and you can use the following solution:

WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.id("id_of_element")));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", element)

You're passing that element from javascript to java and back to javascript. That's a bad idea, by the time it makes that round trip it might not be there anymore.

((JavascriptExecutor) driver).executeScript("document.querySelector('#id_of_element').scrollIntoView(true);");

Also, a lot of things that you needed to scroll into view for (with older seleniums), you no longer do.

Related