How to Scroll to an Element
Usually when using selenium, scrolling is performed automatically when your test performs an action against the element in question. However, sometimes the element either cannot be interacted with, or it is not currently displayed due to a "scroll to reveal" page behaviour. Therefore, it is useful to know how to actually force the element to scroll up or down.
This article will cover scrolling to a specific element, as well as a more general-purpose untargeted scrolling command.
Scrolling to an element without interacting with it
To scroll to a specific element without clicking or sending keys to it, you can use the Actions driver method moveToElement(element), where element is the element you want to move to. This will scroll the minimum distance required to show the element on the screen.
Here is some example code showing this method in action:
WebElement otherAreasSection = driver.findElement(By.xpath("//*[@id='Other_areas_of_Wikipedia']")); Actions actions = new Actions(driver); actions.moveToElement(otherAreasSection).build().perform();
This code snippet is used in a case to move the minimum distance to reveal the title of Wikipedia's "Other areas of Wikipedia" section.
The snippet used above has an associated test case that accesses the correct page of wikipedia in order to then scroll and reveal the title of the section titled "Other areas of Wikipedia". There is a pause before the end of the test, so you can see the results in the live video feed. If you want to see the case being run, click here:
Scrolling by a certain number of pixels
Sometimes the page accessed in your testing scenario requires you to scroll to reveal more elements that you need to interact with. Often an easy solution would be to use the method detailed above to just scroll to an element at the bottom of the page. However, sometimes this is not viable so here we will detail how to scroll without using any elements.
Here is an example of how you would use it in code:
This code snippet is used in a case to scroll down by 750 pixels.
The snippet used above has an associated test case that accesses the correct page of wikipedia in order to then scroll and reveal the section titled "Other areas of Wikipedia". There is a pause before the end of the test, so you can see the results in the live video feed. If you want to see the case being run, click here: