Waiting for a scroll to be over



  • I have this function who scroll an element into view and then click on it:

        private void iClickOnElement(WebElement element){
            WebDriverWait wait = new WebDriverWait(driver, 10);
            wait.until(ExpectedConditions.elementToBeClickable(element));
    
            String scrollElementIntoMiddle = "var viewPortHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);"
                    + "var elementTop = arguments[0].getBoundingClientRect().top;"
                    + "window.scrollBy(0, elementTop-(viewPortHeight/2));";
    
            ((JavascriptExecutor) driver).executeScript(scrollElementIntoMiddle, element);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            element.click();
        }
    

    Since the scroll is "smooth", I added a "sleep()" to make sure the element is actually scrolled into view before I click on it.

    However, using the sleep is ugly and I would like to just be able to wait for the scroll to be over before I click on anything. How can I do that?

    I'm aware of this question but I'm not good enough with javascript interacting with selenium to make use of it.



  • Below are my methods to scroll into view:

    /**
     * Wait until JQuery is inactive
     * @author M1033792 - Bill Hileman
     */
    public void waitForJQueryToBeInactive() {
    
        Boolean isJqueryUsed = (Boolean) ((JavascriptExecutor) driver)
                .executeScript("return (typeof(jQuery) != 'undefined')");
    
        if (isJqueryUsed) {
            while (true) {
                // JavaScript test to verify jQuery is active or not
                Boolean ajaxIsComplete = (Boolean) (((JavascriptExecutor) driver)
                        .executeScript("return jQuery.active == 0"));
                if (ajaxIsComplete)
                    break;
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
            }
        }
    
    }
    
    /** 
     * Scroll a web element into view
     * @author M1033792 - Bill Hileman
     * @param ele - WebElement
     */
    public void scrollIntoView(WebElement ele) {
    
        ((JavascriptExecutor)driver).executeScript("window.scrollTo(" + ele.getLocation().x + 
                                                                    "," + ele.getLocation().y + ")");
        waitForJQueryToBeInactive();
    
    }
    


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2