πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Scenarios
Scenario 68 of 100
JavaScript Executor
Beginner

Scrolling Page and Elements with JavaScript

πŸ“œScenario Overview

Scrolling Page and Elements with JavaScript

Key Takeaways & Cheat Sheet

  • βœ“Use window.scrollBy() to scroll by a set pixel offset
  • βœ“Use window.scrollTo() to scroll to absolute page coordinates
  • βœ“Use scrollIntoView() to scroll elements directly into the viewport
  • βœ“Cast the driver instance to JavascriptExecutor to run scripts

Short Direct Answer

To scroll pages or move elements into the viewport, cast your driver to `JavascriptExecutor`. Use `scrollIntoView(true)` to bring elements into view, or use `window.scrollBy(x, y)` to scroll by a set pixel offset.

⚠️ Senior Warning (Red Flag)

Avoid using arbitrary hardcoded coordinates like scroll(0, 1500). Responsive layouts have variable page heights, which can cause elements to be missed.

πŸ’‘ STAR Deep Dive Explanation & Pro Tip

Scrolling dynamically to the center of the viewport keeps target elements clear of sticky headers and bottom banners.

SeleniumAutomation.java
Selenium 4 + Java
JavascriptExecutor js = (JavascriptExecutor) driver;

// βœ… 1. Scroll dynamically by 500 vertical pixels
js.executeScript("window.scrollBy(0, 500);");

// βœ… 2. Scroll to the absolute bottom of the page
js.executeScript("window.scrollTo(0, document.body.scrollHeight);");

// βœ… 3. Scroll specific element into the center of the viewport
WebElement element = driver.findElement(By.id("footer-links"));
js.executeScript("arguments[0].scrollIntoView({block: 'center'});", element);