Home > Software design >  Gradually scroll to element in Selenium
Gradually scroll to element in Selenium

Time:10-28

(Java). Currently trying to reach a 'next' button that is located at the bottom of the page, the JavaScript script "executeScript("arguments[0].scrollIntoView(true);" properly takes me to the element but I want to reach it gradually. For example, scroll 500 pixels at a time until the element is scrolled into view.

I have tried getting the y location of the element and then using the scrollTo element inside a loop to reach every 1% of the y value but I face some issues with the pixels so this approach doesn't work. This is something I have so far that takes me to the element, but it does it instantly

WebElement next = driver.findElement(By.xpath("..."));
            jas.executeScript("arguments[0].scrollIntoView(true);", next)

CodePudding user response:

Try this one

JavascriptExecutor js=(JavascriptExecutor)driver; js.executeScript("window.scrollBy(x-axis,y-axis)");

CodePudding user response:

I managed to get it to work, here is how I did it.

WebElement next = driver.findElement(By.xpath(...));
JavascriptExecutor jas = (JavascriptExecutor) driver;
long value = (long) 0;
while (value   500 < next.getLocation().getY())
        {
            value = (Long) jas.executeScript("return window.pageYOffset;");
            jas.executeScript("window.scrollBy(0,500)");
            Thread.sleep(100);
        }
  • Related