0

I experience this behavior of scroll into view. Normally, I scroll elements into view with Actions or JavaScript like following:

Actions actions = new Actions(driver());
actions.moveToElement(element).build().perform();

or

js().executeScript("arguments[0].scrollIntoView();", element);

Both of them work fine when the elements are out of viewport. But sometimes, my elements are already inside the viewport, then when it reaches these commands, it actually scrolls these element out of view, and the test fails, because it is not clickable.

Has anyone experienced the same issue? Any solution?

Ragnarsson
  • 1,715
  • 7
  • 41
  • 74
  • Have you tried finding the element first and then scroll ? Using : if(driver.findElements(By.xpath("value")).size() != 0){ System.out.println("Element is Present"); }else{ js().executeScript("arguments[0].scrollIntoView();", element); } – Avataar17 Mar 06 '20 at 11:03
  • What about `jse.executeScript("arguments[0].scrollIntoView(true);", element);` ? – NarendraR Mar 06 '20 at 11:31
  • @Avataar17: Hi, the if else doesn't help either, because the element is always there, it is just not into the viewport – Ragnarsson Mar 06 '20 at 12:47
  • @NarendraR: Hi, I tried with true, it still scrolls the element out of view when element is already inside the view – Ragnarsson Mar 06 '20 at 12:48

1 Answers1

0

You can check if element is in view port or not and based on the boolean, you can put the action, to find out if element is in the view port I use

public static Boolean isVisibleInViewport(WebElement element) {
WebDriver driver = ((RemoteWebElement)element).getWrappedDriver();

return (Boolean)((JavascriptExecutor)driver).executeScript(
  "var elem = arguments[0],                 " +
  "  box = elem.getBoundingClientRect(),    " +
  "  cx = box.left + box.width / 2,         " +
  "  cy = box.top + box.height / 2,         " +
  "  e = document.elementFromPoint(cx, cy); " +
  "for (; e; e = e.parentElement) {         " +
  "  if (e === elem)                        " +
  "    return true;                         " +
  "}                                        " +
  "return false;                            "
  , element);
}

Reference

Viki
  • 157
  • 1
  • 3