marwaha.ks
marwaha.ks

Reputation: 549

Scroll until element is in DOM

Hi there I'm using this code to try and scroll the page until element is in the DOM. However it the page doesn't scrol, it just loops and loops over. Is my IJavaScriptExecutor wrong?

public static void ScrollUntilElementinDom(this IWebDriver driver, By by)
{
    bool isPresent = false;
    while (isPresent == false)
    {
        try
        {
            isPresent = driver.FindElement(by).Displayed;
        }
        catch (Exception)
        {

        }
        if (isPresent == true)
        {
            break;
        }
        else
        {
            ((IJavaScriptExecutor) driver).ExecuteScript("window.scrollBy(100,0);");

        }

    }

Upvotes: 0

Views: 1006

Answers (3)

Guy
Guy

Reputation: 50919

Try to scroll with Actions

Actions action = new Actions(driver);
action.MoveToElement(driver.FindElement(by)).Build().Perform();

And to find if the element is displayed you can use explicit wait

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));

try
{
    wait.Until(ExpectedConditions.ElementIsVisible(by));
    isPresent = true;
}
catch (Exception) { }

This will wait up to 15 seconds for the element to be visible.

Upvotes: 1

Shibu Thomas
Shibu Thomas

Reputation: 3196

You should use Actions class to perform scrolling to element.

WebElement element = driver.findElement(By.id("element-id"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();

Upvotes: 0

Ben
Ben

Reputation: 35653

  • You are scrolling the window to trigger loading of further content.
  • You wish to continue scrolling the window, until the content you seek has been loaded.

You need to wait for the content to load.

At no point are you waiting. Consider WebDriverWait

Upvotes: 2

Related Questions