Scroll Page in Selenium WebDriver
Scrolling a web page is an important browser automation operation in Selenium WebDriver. Modern websites often contain long pages, dynamic sections, product listings, forms, tables, dashboards, footer sections, and lazy-loaded content that may not be visible in the current browser viewport. Selenium automation may therefore need to scroll the page before interacting with or validating specific elements.
In Selenium with Java, page scrolling can be handled using Selenium's Actions API or JavaScriptExecutor. JavaScriptExecutor is especially useful when the automation script needs precise control over the browser's scroll position or needs to scroll directly to a particular WebElement.
Course Resource: Selenium Training Course | Register for Course Demo
1. What is Scroll Page in Selenium?
Scroll Page in Selenium means moving the browser viewport vertically or horizontally so that content outside the currently visible area becomes accessible.
For example, if a Submit button is located at the bottom of a long registration page, Selenium may need to scroll the page until the button is visible before performing an action.
Open Web Page
↓
Locate Target Element
↓
Check Current Viewport
↓
Scroll Page
↓
Target Becomes Visible
↓
Perform Action
↓
Validate Result
2. Why is Page Scrolling Required?
Scrolling is useful whenever the target content is outside the current viewport or when scrolling itself triggers additional application behavior.
- To access elements below the visible viewport.
- To interact with buttons at the bottom of long pages.
- To test long registration forms.
- To validate footer sections.
- To test product listings.
- To work with large web tables.
- To trigger lazy-loaded content.
- To test infinite-scroll pages.
- To validate dynamic web applications.
- To capture screenshots of specific page sections.
- To test responsive layouts.
3. Selenium Scrolling Techniques
There are several approaches to scrolling in Selenium.
| Technique | Purpose |
| JavaScriptExecutor | Programmatically control browser scrolling |
| Actions.scrollByAmount() | Scroll by a specific amount |
| Actions.scrollToElement() | Scroll directly to an element |
| scrollIntoView() | Bring a particular DOM element into the viewport |
| Container scroll | Scroll an internal div or panel |
| Keyboard actions | Use PAGE_DOWN, PAGE_UP, HOME and END |
4. What is JavascriptExecutor?
JavascriptExecutor is a Selenium interface that allows Java Selenium programs to execute JavaScript inside the browser's current page context.
It is commonly used for specialized browser operations such as scrolling, reading page properties, interacting with DOM properties, checking page readiness, highlighting elements, and performing other JavaScript-based operations.
5. Import JavascriptExecutor
import org.openqa.selenium.JavascriptExecutor;
6. Create JavascriptExecutor Object
JavascriptExecutor js = (JavascriptExecutor) driver;
The WebDriver object is type-cast to JavascriptExecutor so JavaScript can be executed through Selenium.
7. Scroll Down Using JavaScript
The window.scrollBy() method can be used to move the browser viewport by a specified number of pixels.
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,500);");
Here, 0 represents horizontal movement and 500 represents vertical movement.
8. Scroll Down by 1000 Pixels
js.executeScript("window.scrollBy(0,1000);");
This moves the page approximately 1000 pixels downward.
9. Scroll Up the Page
A negative vertical value can be used to scroll upward.
js.executeScript("window.scrollBy(0,-500);");
10. Scroll Horizontally
Horizontal scrolling can be performed by changing the first value.
js.executeScript("window.scrollBy(500,0);");
11. Scroll to the Top of the Page
The window.scrollTo() method can move the page directly to a specific coordinate.
js.executeScript("window.scrollTo(0,0);");
12. Scroll to the Bottom of the Page
js.executeScript(
"window.scrollTo(0, document.body.scrollHeight);"
);
document.body.scrollHeight represents the total height of the page content.
13. Difference Between scrollBy() and scrollTo()
| Method | Meaning | Example |
| scrollBy() | Moves relative to the current position | window.scrollBy(0,500) |
| scrollTo() | Moves to an absolute position | window.scrollTo(0,1000) |
14. Scroll to a Specific WebElement
Instead of guessing the number of pixels, Selenium can scroll directly to a target element.
WebElement element = driver.findElement(By.id("footer"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(
"arguments[0].scrollIntoView(true);",
element
);
15. Understanding scrollIntoView()
The JavaScript scrollIntoView() method scrolls the page until the specified DOM element is visible in the viewport.
arguments[0].scrollIntoView(true);
When the element is passed as an argument from Selenium, it becomes arguments[0] inside the JavaScript code.
16. Understanding arguments[0]
arguments[0] represents the first argument supplied to JavaScriptExecutor.
WebElement button = driver.findElement(By.id("submit"));
js.executeScript(
"arguments[0].scrollIntoView(true);",
button
);
Here, button is passed as the first argument and becomes arguments[0].
17. Scroll Element to Center
Centering an element can be useful on pages with sticky headers or fixed navigation bars.
WebElement element = driver.findElement(By.id("submit"));
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
element
);
18. Scroll Element to Top
js.executeScript(
"arguments[0].scrollIntoView({block:'start'});",
element
);
19. Scroll Element to Bottom
js.executeScript(
"arguments[0].scrollIntoView({block:'end'});",
element
);
20. Scroll Element with Nearest Alignment
js.executeScript(
"arguments[0].scrollIntoView({block:'nearest'});",
element
);
The nearest option attempts to move the minimum amount necessary to make the element visible.
21. Scroll Element Horizontally and Vertically
js.executeScript(
"arguments[0].scrollIntoView({block:'center', inline:'center'});",
element
);
22. Scrolling with Selenium Actions
Selenium's Actions class provides scrolling capabilities through WebDriver input actions.
Actions actions = new Actions(driver);
actions.scrollByAmount(0, 500).perform();
23. Required Actions Import
import org.openqa.selenium.interactions.Actions;
24. Scroll to Element Using Actions
WebElement element = driver.findElement(By.id("target"));
Actions actions = new Actions(driver);
actions.scrollToElement(element).perform();
25. JavaScript Scroll vs Actions Scroll
| Feature | JavaScriptExecutor | Actions |
| Pixel scrolling | Yes | Yes |
| Scroll to element | scrollIntoView() | scrollToElement() |
| DOM JavaScript execution | Yes | No |
| Browser-side scripting | Yes | No |
| Input action model | Not its main purpose | Yes |
26. Scroll Using Keyboard Actions
Keyboard keys can also be used for page navigation.
Actions actions = new Actions(driver);
actions.sendKeys(Keys.PAGE_DOWN).perform();
27. Scroll Up Using PAGE_UP
actions.sendKeys(Keys.PAGE_UP).perform();
28. Move to Top Using HOME
actions.sendKeys(Keys.HOME).perform();
29. Move to Bottom Using END
actions.sendKeys(Keys.END).perform();
30. Keyboard Scrolling Comparison
| Key | Typical Purpose |
| PAGE_DOWN | Move viewport downward |
| PAGE_UP | Move viewport upward |
| HOME | Move toward the beginning |
| END | Move toward the end |
31. Scroll Before Clicking
A common Selenium scenario is scrolling an element into view before clicking it.
WebElement button = driver.findElement(By.id("submit"));
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
button
);
button.click();
32. Scroll Before Typing
WebElement address = driver.findElement(By.id("address"));
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
address
);
address.sendKeys("Mumbai");
33. Scroll Before Selecting a Dropdown
WebElement country = driver.findElement(By.id("country"));
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
country
);
Select select = new Select(country);
select.selectByVisibleText("India");
34. Scroll Before Checking a Checkbox
WebElement checkbox = driver.findElement(By.id("terms"));
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
checkbox
);
if (!checkbox.isSelected()) {
checkbox.click();
}
35. Scroll Before Selecting a Radio Button
WebElement radio = driver.findElement(By.id("male"));
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
radio
);
radio.click();
36. Scroll Before Taking Screenshot
Scrolling can be used to position a specific page section before capturing evidence.
WebElement section = driver.findElement(By.id("pricing"));
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
section
);
File screenshot = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
37. Scroll to Footer
WebElement footer = driver.findElement(
By.tagName("footer")
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
footer
);
38. Scroll to Web Table
WebElement table = driver.findElement(
By.id("employeeTable")
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
table
);
39. Scroll to a Form
WebElement form = driver.findElement(
By.id("registrationForm")
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
form
);
40. Scroll to a Link
WebElement link = driver.findElement(
By.linkText("Contact Us")
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
link
);
41. Scroll to a Product
WebElement product = driver.findElement(
By.xpath("//h2[text()='Laptop']")
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
product
);
42. Scrolling in E-Commerce Testing
E-commerce applications often contain long product pages and product listings. Automation may need to scroll to product details, reviews, recommendations, related products, filters, or checkout controls.
WebElement reviews = driver.findElement(
By.id("customer-reviews")
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
reviews
);
Assert.assertTrue(reviews.isDisplayed());
43. Scrolling in Registration Testing
Long registration forms may contain address, employment, preferences, terms, and submission sections below the initial viewport.
WebElement address = driver.findElement(By.id("address"));
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
address
);
address.sendKeys("Mumbai");
44. Scrolling in Checkout Testing
WebElement placeOrder = driver.findElement(
By.id("place-order")
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
placeOrder
);
placeOrder.click();
45. Scrolling and Explicit Wait
Scrolling does not replace synchronization. A page may continue loading even after the browser has navigated to it. Explicit waits should be used when the target element depends on dynamic application behavior.
WebDriverWait wait = new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("target")
)
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
element
);
46. Scroll and Clickable Element
WebDriverWait wait = new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement button = wait.until(
ExpectedConditions.elementToBeClickable(
By.id("submit")
)
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
button
);
button.click();
47. Why Explicit Wait is Important
- The element may not have been created yet.
- The element may not be visible.
- The page may still be loading dynamic content.
- An overlay may temporarily cover the element.
- JavaScript application code may still be updating the DOM.
- The target may become stale after a page update.
48. Scrolling and Sticky Headers
Many modern websites use sticky navigation bars that remain fixed at the top of the browser while the page scrolls. A target element can therefore become technically visible but still be covered by the fixed header.
js.executeScript(
"arguments[0].scrollIntoView(true);",
element
);
js.executeScript("window.scrollBy(0,-100);");
The offset should be adjusted according to the actual fixed header used by the application.
49. Center Scrolling to Handle Sticky Headers
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
element
);
Centering the element can make it easier to interact with when the top of the viewport contains fixed navigation.
50. Scrolling a Specific Container
Not every scroll operation affects the entire browser window. Many applications contain scrollable panels, lists, modals, sidebars, or table containers.
WebElement container = driver.findElement(
By.id("scrollContainer")
);
js.executeScript(
"arguments[0].scrollTop = arguments[0].scrollHeight;",
container
);
51. Scroll Inside a Div
WebElement panel = driver.findElement(
By.cssSelector(".results-panel")
);
js.executeScript(
"arguments[0].scrollTop += 500;",
panel
);
52. Scroll Internal Div to Top
js.executeScript(
"arguments[0].scrollTop = 0;",
panel
);
53. Scroll Internal Div to Bottom
js.executeScript(
"arguments[0].scrollTop = arguments[0].scrollHeight;",
panel
);
54. Window Scroll vs Container Scroll
| Type | JavaScript Example |
| Window vertical scroll | window.scrollBy(0,500) |
| Window top | window.scrollTo(0,0) |
| Window bottom | window.scrollTo(0,document.body.scrollHeight) |
| Container vertical scroll | element.scrollTop |
| Container maximum scroll | element.scrollHeight |
55. Horizontal Scrolling in a Table
Large tables may be wider than the browser viewport and may require horizontal scrolling.
WebElement tableContainer = driver.findElement(
By.cssSelector(".table-container")
);
js.executeScript(
"arguments[0].scrollLeft = arguments[0].scrollWidth;",
tableContainer
);
56. Horizontal Scroll by Pixels
js.executeScript("window.scrollBy(500,0);");
57. Check Current Vertical Scroll Position
Long position = (Long) js.executeScript(
"return window.pageYOffset;"
);
System.out.println("Scroll Position: " + position);
58. Check Page Height
Long height = (Long) js.executeScript(
"return document.body.scrollHeight;"
);
System.out.println("Page Height: " + height);
59. Check Viewport Height
Long viewportHeight = (Long) js.executeScript(
"return window.innerHeight;"
);
System.out.println(
"Viewport Height: " + viewportHeight
);
60. Page Height vs Viewport Height
Complete Page Height
↓
+---------------------------+
| |
| Page Content |
| |
|---------------------------|
| Visible Viewport |
|---------------------------|
| |
| More Content |
| |
+---------------------------+
Page Height > Viewport Height
↓
Scroll
61. Infinite Scrolling
Infinite scrolling is a technique in which additional content is loaded as the user reaches the bottom or near-bottom of a page. Social feeds, product catalogs, news pages, and media applications commonly use this pattern.
Scroll Down
↓
Reach Bottom
↓
Application Requests More Data
↓
New Content Appears
↓
Page Height Changes
↓
Scroll Again
↓
Repeat Until Condition Is Met
62. Basic Infinite Scroll Example
JavascriptExecutor js = (JavascriptExecutor) driver;
long previousHeight = (Long) js.executeScript(
"return document.body.scrollHeight;"
);
while (true) {
js.executeScript(
"window.scrollTo(0, document.body.scrollHeight);"
);
Thread.sleep(1000);
long currentHeight = (Long) js.executeScript(
"return document.body.scrollHeight;"
);
if (currentHeight == previousHeight) {
break;
}
previousHeight = currentHeight;
}
This example demonstrates the basic mechanism. In production automation, explicit synchronization based on the application's loading condition is generally preferable to relying only on a fixed sleep.
63. Infinite Scroll with Target Element
A practical test should usually stop scrolling when the required content is found instead of scrolling indefinitely.
JavascriptExecutor js = (JavascriptExecutor) driver;
for (int i = 0; i < 20; i++) {
List<WebElement> products =
driver.findElements(By.cssSelector(".product"));
boolean found = false;
for (WebElement product : products) {
if (product.getText().contains("Laptop")) {
found = true;
break;
}
}
if (found) {
break;
}
js.executeScript(
"window.scrollBy(0,700);"
);
}
64. Lazy-Loaded Content
Lazy loading means that some page resources or content are loaded only when they approach the visible area. Scrolling can trigger the application to load these resources.
js.executeScript(
"window.scrollTo(0, document.body.scrollHeight);"
);
After scrolling, the test should wait for the expected content or state rather than assuming that the content has loaded immediately.
65. Smooth Scrolling
JavaScript can request smooth scrolling in browsers that support the relevant scrolling behavior.
js.executeScript(
"window.scrollTo({top:1000, behavior:'smooth'});"
);
Smooth scrolling is more relevant to visual behavior. Functional automation generally benefits from deterministic scrolling and appropriate synchronization.
66. Scroll and Visibility Verification
WebElement element = driver.findElement(By.id("target"));
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
element
);
Assert.assertTrue(element.isDisplayed());
67. Scroll and Perform Mouse Action
WebElement element = driver.findElement(By.id("target"));
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
element
);
Actions actions = new Actions(driver);
actions.moveToElement(element).click().perform();
68. Scroll with CSS Selector
WebElement element = driver.findElement(
By.cssSelector("#footer")
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
element
);
69. Scroll with XPath
WebElement element = driver.findElement(
By.xpath("//button[text()='Submit']")
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
element
);
70. Scroll with Name Locator
WebElement element = driver.findElement(
By.name("address")
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
element
);
71. Scroll with Class Name
WebElement element = driver.findElement(
By.className("footer")
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
element
);
72. Scroll and Validate Text
WebElement footer = driver.findElement(
By.cssSelector("footer")
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
footer
);
Assert.assertTrue(
footer.getText().contains("Contact")
);
73. Scroll and Validate URL
WebElement link = driver.findElement(
By.linkText("Contact Us")
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
link
);
link.click();
Assert.assertTrue(
driver.getCurrentUrl().contains("contact")
);
74. Scroll and Validate Page Title
WebElement button = driver.findElement(By.id("dashboard"));
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
button
);
button.click();
Assert.assertEquals(
driver.getTitle(),
"Dashboard"
);
75. Scrolling and ElementClickInterceptedException
ElementClickInterceptedException may occur when another element, popup, overlay, or fixed component is positioned over the target.
Scrolling the target into an appropriate position and waiting for temporary overlays to disappear can often address the problem. JavaScript click should not automatically be used as the first response because the underlying issue may be synchronization or an application-state problem.
76. Scrolling and StaleElementReferenceException
Dynamic applications may replace DOM elements while the page is being scrolled. If a previously located element becomes stale, locate the element again.
WebElement element = wait.until(
ExpectedConditions.presenceOfElementLocated(
By.id("target")
)
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
element
);
77. Scrolling and NoSuchElementException
If the target element cannot be found, scrolling does not solve the locator problem. Verify the locator, page state, frame context, and timing.
78. Scrolling and ElementNotInteractableException
An element can exist in the DOM but still not be ready for interaction. Check visibility, enabled state, overlays, frames, and application synchronization.
79. Scrolling Inside an iframe
If the target element is inside an iframe, Selenium must first switch into the correct frame.
WebElement frame = driver.findElement(
By.id("paymentFrame")
);
driver.switchTo().frame(frame);
WebElement button = driver.findElement(
By.id("submit")
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
button
);
button.click();
driver.switchTo().defaultContent();
80. Scrolling and Multiple Windows
Scrolling applies to the currently active browser window or tab. If the target is in another window, switch to that window first.
driver.switchTo().window(windowHandle);
js.executeScript(
"window.scrollTo(0, document.body.scrollHeight);"
);
81. Scrolling in Responsive Testing
Responsive layouts may change element positions based on browser width and height. Therefore, tests should avoid relying on fixed screen coordinates.
driver.manage().window().setSize(
new Dimension(390, 844)
);
After changing the viewport, the test should locate elements again and use element-based scrolling where appropriate.
82. Scrolling in Headless Testing
Headless browser tests still have a viewport and page scrolling behavior even though the browser window is not displayed to the user.
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new");
options.addArguments("--window-size=1920,1080");
WebDriver driver = new ChromeDriver(options);
83. Scrolling and Browser Zoom
Browser zoom can affect the visual relationship between coordinates and elements. Element-based scrolling is generally more robust than coordinate-based automation.
84. Scrolling and Page Object Model
In a Page Object Model framework, page-specific scrolling can be encapsulated in page methods while generic scrolling functionality can be placed inside a reusable utility class.
public void scrollToSubmitButton() {
WebElement button = driver.findElement(
By.id("submit")
);
JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
button
);
}
85. Reusable Scroll Utility
public class ScrollUtils {
private WebDriver driver;
public ScrollUtils(WebDriver driver) {
this.driver = driver;
}
public void scrollDown(int pixels) {
JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"window.scrollBy(0," + pixels + ");"
);
}
public void scrollUp(int pixels) {
JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"window.scrollBy(0,-" + pixels + ");"
);
}
public void scrollToTop() {
JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"window.scrollTo(0,0);"
);
}
public void scrollToBottom() {
JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"window.scrollTo(0,document.body.scrollHeight);"
);
}
public void scrollToElement(WebElement element) {
JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
element
);
}
}
86. Using Scroll Utility
ScrollUtils scroll = new ScrollUtils(driver);
scroll.scrollDown(500);
scroll.scrollToElement(
driver.findElement(By.id("footer"))
);
scroll.scrollToBottom();
scroll.scrollToTop();
87. Complete Selenium Scroll Example
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ScrollPageExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.manage().window().maximize();
driver.get("https://example.com");
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement footer = wait.until(
ExpectedConditions.presenceOfElementLocated(
By.tagName("footer")
)
);
JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
footer
);
wait.until(
ExpectedConditions.visibilityOf(footer)
);
System.out.println(
"Footer is visible: "
+ footer.isDisplayed()
);
} finally {
driver.quit();
}
}
}
88. Scroll Page with TestNG
import org.testng.Assert;
import org.testng.annotations.Test;
@Test
public void verifyFooterAfterScrolling() {
WebElement footer = driver.findElement(
By.tagName("footer")
);
JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
footer
);
Assert.assertTrue(
footer.isDisplayed()
);
}
89. Practical Test Scenario
- Launch the browser.
- Open the application.
- Maximize or configure the required viewport.
- Locate the target element.
- Wait for the element when necessary.
- Scroll the element into view.
- Verify visibility.
- Perform the required action.
- Validate the expected result.
- Capture evidence if required.
- Close the browser.
90. Real-World Project Example: E-Commerce
Suppose an e-commerce product page contains product information at the top, specifications in the middle, customer reviews below, and related products near the bottom.
WebElement reviews = driver.findElement(
By.id("customer-reviews")
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
reviews
);
Assert.assertTrue(
reviews.isDisplayed()
);
91. Real-World Project Example: Registration
WebElement address = driver.findElement(
By.id("address")
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
address
);
address.sendKeys("Mumbai");
WebElement submit = driver.findElement(
By.id("submit")
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
submit
);
submit.click();
92. Real-World Project Example: Footer Links
WebElement footer = driver.findElement(
By.tagName("footer")
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
footer
);
List<WebElement> links =
footer.findElements(By.tagName("a"));
System.out.println(
"Footer Links: " + links.size()
);
93. Real-World Project Example: Long Dashboard
A dashboard may contain summary cards at the top and reports, charts, tables, and logs farther down the page.
WebElement reportTable = driver.findElement(
By.id("reportTable")
);
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
reportTable
);
Assert.assertTrue(
reportTable.isDisplayed()
);
94. Real-World Project Example: News Website
A news website may use infinite scrolling to load additional articles. Selenium can repeatedly scroll, wait for additional articles, inspect the loaded content, and stop when the required article is found.
for (int i = 0; i < 10; i++) {
List<WebElement> articles =
driver.findElements(By.cssSelector("article"));
boolean found = false;
for (WebElement article : articles) {
if (article.getText().contains("Selenium")) {
found = true;
break;
}
}
if (found) {
break;
}
js.executeScript(
"window.scrollBy(0,700);"
);
}
95. Common Mistake: Using Large Fixed Scroll Values
A command such as window.scrollBy(0,5000) may work on one screen size but behave differently on another page or viewport.
When a target element is known, prefer:
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
element
);
96. Common Mistake: Using Thread.sleep() Everywhere
Fixed sleeps can make tests slower and may still fail when an application takes longer than the chosen delay.
Use explicit waits for application conditions whenever possible.
97. Common Mistake: Assuming Visible Means Clickable
An element can be visible but still be covered by an overlay, disabled, stale, or not ready for interaction.
WebElement button = wait.until(
ExpectedConditions.elementToBeClickable(
By.id("submit")
)
);
98. Common Mistake: Ignoring Scrollable Containers
If the page itself does not move when scrolling, inspect the application for an internal scrollable container.
WebElement panel = driver.findElement(
By.cssSelector(".results-panel")
);
js.executeScript(
"arguments[0].scrollTop = arguments[0].scrollHeight;",
panel
);
99. Common Mistake: Using Coordinates
Coordinate-based scrolling and clicking can become unreliable because browser size, responsive layouts, zoom, operating system settings, and page changes can affect coordinates.
Stable locators and element-based operations are generally easier to maintain.
100. Common Mistake: Using JavaScript for Everything
JavaScriptExecutor is powerful but should not automatically replace Selenium's normal APIs.
For normal interactions, prefer Selenium methods when they work correctly:
element.click();
element.sendKeys("text");
Actions actions = new Actions(driver);
actions.moveToElement(element).click().perform();
101. Best Practice: Scroll to the Target Element
When a specific element is the subject of the test, element-based scrolling is usually more maintainable than guessing a pixel amount.
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
element
);
102. Best Practice: Use Explicit Synchronization
WebElement target = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("target")
)
);
103. Best Practice: Consider Fixed Headers
Use center alignment or a small scroll offset when fixed headers cover elements after scrolling.
104. Best Practice: Validate the Business Result
Scrolling is usually an intermediate step. The test should validate the actual expected behavior after scrolling.
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
button
);
button.click();
Assert.assertTrue(
driver.getCurrentUrl().contains("dashboard")
);
105. Best Practice: Re-Locate Dynamic Elements
When scrolling causes the application to refresh or replace DOM elements, locate the required element again instead of assuming the old WebElement reference remains valid.
106. Best Practice: Keep Scroll Methods Reusable
Common scrolling operations such as scroll top, scroll bottom, scroll by pixels, and scroll to element can be placed in reusable utility classes.
107. Best Practice: Handle Frames Correctly
If the target element is inside an iframe, switch to the correct frame before locating and scrolling to the element.
108. Best Practice: Test Different Viewports
Responsive pages can change layout and scrolling behavior at different browser dimensions. When required, execute the same scrolling scenario at multiple viewport sizes.
109. Selenium Scroll Page Interview Questions
Q1. How do you scroll down a webpage in Selenium?
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,500);");
Q2. How do you scroll to the bottom of a webpage?
js.executeScript(
"window.scrollTo(0, document.body.scrollHeight);"
);
Q3. How do you scroll to the top?
js.executeScript("window.scrollTo(0,0);");
Q4. How do you scroll to a specific WebElement?
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
element
);
Q5. What is the difference between scrollBy() and scrollTo()?
scrollBy() moves the viewport relative to its current position, while scrollTo() moves it to an absolute position.
Q6. Can Selenium scroll without JavaScript?
Yes. Selenium's Actions API provides scrolling operations, including scrolling by an amount and scrolling to an element.
Q7. How do you scroll inside a div?
js.executeScript(
"arguments[0].scrollTop = arguments[0].scrollHeight;",
element
);
Q8. What is infinite scrolling?
Infinite scrolling is a page design where additional content is loaded as the user approaches the bottom of the page.
Q9. Does scrolling guarantee that an element is clickable?
No. The element may still be covered, disabled, stale, or affected by application synchronization issues.
Q10. Why is scrollIntoView() useful?
It allows automation to bring a specific element into the viewport without relying on an arbitrary pixel distance.
110. Quick Revision Table
| Requirement | Code |
| Scroll down | window.scrollBy(0,500) |
| Scroll up | window.scrollBy(0,-500) |
| Scroll top | window.scrollTo(0,0) |
| Scroll bottom | window.scrollTo(0,document.body.scrollHeight) |
| Scroll to element | arguments[0].scrollIntoView() |
| Scroll using Actions | actions.scrollByAmount(0,500).perform() |
| Scroll to element using Actions | actions.scrollToElement(element).perform() |
| Container scroll | arguments[0].scrollTop |
111. Scroll Page Automation Checklist
- Identify whether the browser window or an internal container needs scrolling.
- Locate the target element using a stable locator.
- Use explicit waits for dynamic content.
- Prefer element-based scrolling when the target is known.
- Consider sticky headers and fixed overlays.
- Handle iframes and windows correctly.
- Use Actions when input-based scrolling is appropriate.
- Use JavaScriptExecutor when precise browser-side scrolling is required.
- Avoid unnecessary fixed sleeps.
- Avoid coordinate-based automation when stable element locators are available.
- Validate the expected result after scrolling.
- Keep reusable scrolling operations in utility methods.
112. Complete Scroll Page Flow
Start Test
↓
Launch Browser
↓
Open Application
↓
Identify Target
↓
Wait for Required Condition
↓
Determine Scroll Type
↓
┌──────────────────────────────┐
│ Window / Element / Container │
└──────────────────────────────┘
↓
Scroll Into Required Position
↓
Verify Visibility / State
↓
Perform Action
↓
Validate Result
↓
Capture Evidence
↓
End Test
113. Selenium Training and Learning Resource
JustAcademy's Selenium Automation Testing course provides training resources covering Selenium WebDriver, Java automation, locators, browser automation, TestNG, data-driven testing, Page Object Model, cross-browser testing, automation frameworks, practical projects, and related testing tools.
Selenium Training Course
Register for Course Demo
114. Conclusion
Page scrolling is an essential Selenium WebDriver skill for testing long, dynamic, responsive, and content-heavy web applications. Selenium provides multiple approaches, including JavaScriptExecutor, Actions scrolling, keyboard actions, element-based scrolling, and scrolling inside individual containers.
For reliable automation, the focus should not be only on moving the page. A good Selenium test identifies the correct target, waits for the required application state, scrolls the target into a suitable viewport position, performs the intended interaction, and validates the expected result.
By practicing scroll-by-pixels, scroll-to-top, scroll-to-bottom, scroll-to-element, container scrolling, horizontal scrolling, infinite scrolling, lazy-loaded content, and scrolling with explicit waits, testers can handle a wide range of real-world Selenium automation scenarios.