Yoda
Yoda

Reputation: 18068

How to determine if scrolling to the element is actually necessary?

I run multiple E2E scenarios, in one of the scenarios scrolling appeared to the element to be only solution to dependably click given link. However, that introduced 200% time execution increase, because driver tries to scroll for each element, as I would like to have universal method for clicking links with given text would like to avoid unnecessary scrolling.

Is there a method to determine if element is displayed in the viewport and one doesn't need to scroll to it?

Upvotes: 1

Views: 330

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193308

A bit unclear in which circumstances you have concluded scrolling appeared to the element to be only solution to dependably click given link. Ideally, if your usecase is to invoke click() on the element, ideally you need to use the ExpectedConditions as element_to_be_clickable() as follows:

new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("element_css"))).Click();

You can find a couple of detailed discussions in:


If scrolling appeares mandatory, to scroll an element within the Viewport before invoking click() you can also use the Element.scrollIntoView() method.

You can find a detailed discussion in: - What is the difference between the different scroll options?


At this point it is worth to mention, the following methods:

will automatically scroll the element within the Viewport.

You can find a detailed discussion in:

Upvotes: 0

Guy
Guy

Reputation: 50919

The preconditions for clickable IWebElement are Displayed and Enabled

IWebElement element = driver.FindElement(...);
if (!(element.Displayed && element.Enabled))
{
    //scroll to the element
}
element.Click();

*You can probably drop the element.Enabled check, it will return false only if the element is explicitly disabled. If you can click it after the scroll, it's enabled.

The Enabled property will generally return true for everything except explicitly disabled input elements.

Upvotes: 2

Related Questions