0

I want to click on a web-element and perform some action. For that, the element needs to be visible. I have written the below code:

WebElement element = driver.findElement(By.xpath("//div//span[@title='Brand']"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500);

Which performs the vertical scroll up to the web-element that is not visible. But the problem is, the code is scrolling beyond the element and the element is going up. I want to scroll up to the web-element.

1
  • Do you mean your element is still out of the view after scroll?
    – Alexey R.
    Oct 27, 2020 at 20:33

1 Answer 1

1

This will work:

webdriver.executeScript("arguments[0].scrollIntoView(true); window.scrollBy(0, -window.innerHeight / 2);", element);

The method scrollIntoView can scroll the element at the top or at the bottom of the view with the default being at the top:

https://developer.mozilla.org/en/docs/Web/API/Element/scrollIntoView

Below are the supported options:

element.scrollIntoView();
element.scrollIntoView(false);
element.scrollIntoView({block: "end"});
element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});

Try without passing any argument :

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

So you could scroll it at the bottom instead:

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

You could also scroll it at the top and then by a 1/4th of the height of the view:

webdriver.executeScript("arguments[0].scrollIntoView(true); window.scrollBy(0, -window.innerHeight / 4);", element);

Or just below a element , eg fixed header:

webdriver.executeScript("arguments[0].scrollIntoView(true); window.scrollBy(0, -arguments[1].offsetHeight);", element, header);

Reference: Scroll Element into View with Selenium

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.