Sometimes, elements on a webpage are not visible until you scroll down. Scrolling into view helps you bring those elements into the visible area so you can interact with them.
0
0
Scrolling into view in Selenium Java
Introduction
When a button or link is below the visible part of the page and you want to click it.
When you need to check or read text that is not currently visible on the screen.
When an element is hidden because the page is long and requires scrolling.
When automated tests fail because the element is not interactable until scrolled into view.
Syntax
Selenium Java
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView(true);", element);This uses JavaScript to scroll the page until the element is visible.
"arguments[0]" refers to the element passed as a parameter.
Examples
Scrolls the page to bring the element with id 'submit-button' into view.
Selenium Java
WebElement element = driver.findElement(By.id("submit-button")); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].scrollIntoView(true);", element);
Scrolls down to the footer element at the bottom of the page.
Selenium Java
WebElement footer = driver.findElement(By.tagName("footer")); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].scrollIntoView(true);", footer);
Sample Program
This test opens a long webpage, finds an element by its id, scrolls it into view, and prints a success message.
Selenium Java
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; public class ScrollIntoViewTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com/longpage"); WebElement element = driver.findElement(By.id("target-element")); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].scrollIntoView(true);", element); System.out.println("Scrolled into view successfully."); } finally { driver.quit(); } } }
OutputSuccess
Important Notes
Make sure the element exists before scrolling to avoid errors.
Scrolling into view does not guarantee the element is clickable; sometimes you may need to wait for it.
Summary
Scrolling into view helps interact with elements not visible on the screen.
Use JavascriptExecutor with scrollIntoView method in Selenium Java.
Always verify the element is present before scrolling.