0

I'm creating some Selenium tests in JavaScript. I'm having trouble clicking on a button that is not in view (this seems to be an issue with the chrome driver). A workaround to this problem is simply scrolling to the element, however the examples shown are in Java, not JavaScript. Based on the solutions for java I tried the following without success:

    var element = driver.findElement(webdriver.By.id('next_button'));
    var location = element.getLocation();
    var window = new webdriver.Window(driver);
    window.scrollBy(location);

I don't think I'm using the right type of window object here. How do I scroll down to the element using JavaScript?

2

1 Answer 1

1

getLocation() function returns the location in the form of an object. Moreover, window.scrollBy() is a DOM javascript function, so you cannot probably use it in selenium without executing it. Also window.scrollBy() scrolls particular number of pixles in the DOM, instead use window.scrollTo() which scrolls to a particular location. Here's how you can do it -

driver.wait(function(){
driver.findElement(By.id('next_button'), function(ele){
    ele.getLocation().then(function(loc){
        driver.executeScript('return window.scrollTo('+loc.x+','+loc.y+');')
        .then(function(){
            ele.click();
        });
    });
});
},10000);

Hope this helps.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer. I had to chain findElement and getLocation with a .then in order to get this to synchronize properly. Unfortunately the page didn't scroll with this, I get the same error on the next_button not being visible. Is the browser object in your example a normal chrome driver object?
Thanks for the update. I placed a sleep on the line before the click in your code, however I still cannot see any scrolling, and I still end up with the same error message at the click.
Can you console the loc variable and see if it is returning the object with any valid value? Also waiting for element to load would help i suppose, if its not in DOM already. Thanks
From the console I get that loc.x = 429.5 and loc.y = 1044.6875. I tried to manually input anywhere between 0-3000 for x and y positions instead of using getLocation, however still nothing happens. Just to confirm that scrolling would indeed solve my problem, I tried to manually scroll during the 5 second wait right before ele.click() and indeed the rest of my code executed without errors.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.