Javascript Scroll Element into View with Selenium used in a wrong way
Tamás B?jte
SDET, Automation Engineer, Test Architect, Contractor, Freelancer @ Remote Work | ISTQB, Oracle Certified
Everybody is pleased with the tests until some functionality is changed in the Front End, and tests are going to fail because the elements are not displayed. You are going to search for solutions for making the web element to be in the clickable state.
You have a considerable probability to find :
WebElement element = driver.findElement(By.id("id_of_element")); driver.executeScript("arguments[0].scrollIntoView(true);", element);
By using this code snippet, we are using the default settings :
If true, the top of the element will be aligned to the top of the visible area of the scrollable ancestor. Corresponds to scrollIntoViewOptions: {block: "start", inline: "nearest"}. This is the default value.
accordingly, this link.
After playing in the chrome console, I discovered that the correct way of using the method is
WebElement element = driver.findElement(By.id("id_of_element")); String script = "arguments[0].scrollIntoView({behavior: \"auto\", block: \"center\", inline: \"center\"});"; driver.executeScript(script, element);
Okay, too much theory, now let's make some things to happen by applying what we learned.
Steps to play:
- Open this link.
- Open the Chrome console(F12 or the dev tools)
- Go to console
- And execute the scripts:
var element = document.getElementById("Notes"); element.scrollIntoView();
var element = document.getElementById("Notes"); element.scrollIntoView(false);
var element = document.getElementById("Notes"); element.scrollIntoView({block: "center"});
var element = document.getElementById("Notes"); element.scrollIntoView({behavior: "smooth", block: "center", inline: "center"});
By running these scripts, I discovered that I am using in a wrong way the javascript code, and if you run as well, you will find the magic word center.