Scrolling webpage using JavaScript

In this post, we will discuss, scrolling webpage using JavaScript. We will look at Facebook front page and try to scroll to the bottom with sample code snippet. I will locate the “Developer” link at the bottom of the Facebook page and scroll the webpage and take a screenshot.


Vertical Scrolling a webpage

public class ScrollPageExample {
    WebDriver driver;

    public void openBrowser() {
        System.setProperty("webdriver.edge.driver", "MicrosoftWebDriver.exe");
        driver=new EdgeDriver();
    public void scrollWebPageToElement() {
        WebElement element = driver.findElement(By.linkText("Developers"));
        ((JavascriptExecutor) driver).executeScript(
                "arguments[0].scrollIntoView();", element);
        WebDriverWait wait = new WebDriverWait(driver, 120);
    public void captureScreen(String fileName) {
        File scrFile = ((TakesScreenshot) driver)
        try {
            FileUtils.copyFile(scrFile, new File(fileName));
        } catch (IOException e) {
    public void closeBrowser() {


The method scrollIntoView() very useful method while applying scrolling property to HTML page, div or frame.t scrolls the page, div or frame until the searching element is in the view.

JavaScript scrollIntoView() method

Syntax :




Unlike the above example, If you know the exact distance to scroll, we can use the below code :


//  vertical scroll - down by 500 pixels
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,500)");
//  vertical scroll - UP by 100 pixels
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,-100)");


Horizontal Scrolling a webpage

Horizontal scroll examples:

// horizontal scroll - right by 30 pixels
js.executeScript("window.scrollBy(30,0)", "");

// horizontal scroll - left by 100
js.executeScript("window.scrollBy(-100,0)", "");