</>

Technology

Selenium

Difficulty

Beginner

Interview Question

How to scroll down a page using JavaScript in Selenium?

Use JavascriptExecutor with window.scrollBy(x, y) to scroll the page by a specified number of pixels in Selenium.

Answer

Scrolling Down a Page Using JavaScript in Selenium

Use JavascriptExecutor to execute JavaScript''s window.scrollBy() function to scroll the page by a specified pixel offset.

Basic scroll down:

Java
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0, 500)");  // Scroll down 500 pixels
Syntax: window.scrollBy(x, y)
  • x = horizontal scroll (pixels) — use 0 for vertical-only scroll
  • y = vertical scroll (pixels) — positive = down, negative = up

Common scroll patterns:

Java
JavascriptExecutor js = (JavascriptExecutor) driver;

// Scroll down 500px
js.executeScript("window.scrollBy(0, 500)");

// Scroll up 300px
js.executeScript("window.scrollBy(0, -300)");

// Scroll to bottom of page
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");

// Scroll to top of page
js.executeScript("window.scrollTo(0, 0)");

// Scroll to specific coordinates
js.executeScript("window.scrollTo(0, 1000)");

Full test example:

Java
@Test
public void scrollTest() {
    driver.get("https://example.com/long-page");

    JavascriptExecutor js = (JavascriptExecutor) driver;

    // Scroll down to load lazy content
    js.executeScript("window.scrollBy(0, 500)");
    Thread.sleep(1000);

    // Verify element is now visible after scroll
    WebElement element = driver.findElement(By.id("lazy-section"));
    Assert.assertTrue(element.isDisplayed());

    // Scroll back to top
    js.executeScript("window.scrollTo(0, 0)");
}

When to use JavaScript scrolling:

  • Elements that load lazily as you scroll
  • Infinite scroll pages
  • Fixed headers blocking element interaction
  • Elements not interactable until scrolled into view

Alternative — Actions class scroll (Selenium 4):

Java
// Selenium 4+
Actions actions = new Actions(driver);
actions.scrollByAmount(0, 500).perform();

Follow AutomateQA

Related Topics