Scrolling to a Particular Element in Selenium
Use JavascriptExecutor with the scrollIntoView() JavaScript method to bring a specific element into the visible viewport.
Basic example:
Java
WebElement element = driver.findElement(By.id("targetElement"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView();", element);
scrollIntoView with alignment options:
Java
// Scroll to element, align to top of viewport
js.executeScript("arguments[0].scrollIntoView(true);", element);
// Scroll to element, align to bottom of viewport
js.executeScript("arguments[0].scrollIntoView(false);", element);
// Scroll with smooth behavior and center alignment
js.executeScript("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});", element);
Full test example — click element after scrolling:
Java
@Test
public void scrollAndClickTest() {
driver.get("https://example.com/long-page");
// Find the element (may be off-screen)
WebElement submitBtn = driver.findElement(By.id("submitBtn"));
// Scroll to it
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView(true);", submitBtn);
// Wait for it to be visible and click
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
wait.until(ExpectedConditions.elementToBeClickable(submitBtn));
submitBtn.click();
Assert.assertEquals(driver.getTitle(), "Confirmation Page");
}
Common issue — fixed header covers element after scroll:
Java
// Scroll into view then adjust for fixed header (e.g., 100px header)
js.executeScript("arguments[0].scrollIntoView(true);", element);
js.executeScript("window.scrollBy(0, -100);"); // Scroll back up 100px
scrollIntoView vs scrollBy comparison:
| Method | Use when |
|---|---|
scrollIntoView(element) | You know the target element |
scrollBy(0, pixels) | You want to scroll a specific pixel amount |
scrollTo(0, height) | You want to go to a specific Y coordinate |
Selenium 4 alternative:
Java
// Selenium 4+
Actions actions = new Actions(driver);
actions.scrollToElement(element).perform();
