Need Help With QA Automation?

Work with our skilled full stack experts to improve your software quality, accelerate testing cycles, and enhance overall performance.

Hire Full Stack Developers

Support On Demand!

Yes, you can scroll to the top of a webpage using JavaScript, similar to how you scroll to the bottom. To scroll to the top of the page, you can set the scroll position to 0 for both the horizontal and vertical scroll:

window.scrollTo(0, 0);

This line of code will scroll the webpage to the very top left corner (horizontal scroll position 0 and vertical scroll position 0).

If you’re using this in a Selenium WebDriver script in Java, you would execute this JavaScript command using the JavascriptExecutor interface like so:

Java

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
// other imports...
public class ScrollToTopExample {
    public static void main(String[] args) {
        WebDriver driver = //... initialize your driver

        // ... your code to navigate to the webpage or perform actions

        // Scroll to the top of the page
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("window.scrollTo(0, 0);");

        // ... other actions or closing the driver
    }
}

 

Related Q&A