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 + JavaJavascriptExecutor 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);