How to Scroll Element into View with Selenium

1 min


646
1 comment, 646 points
Scroll Element into View
Scroll Element into View

Scroll Element into View with Selenium

As we all know Scrolling to the element happens implicitly so you just need to find the item and then work with it. Well all good when I was running the tests with chromedriver and chrome xvfb headless. So when I had to go with my tests  cross browser I figure out that on Firefox and IE I need to use Scroll Element into View , otherwise my tests will fail.

Solution:

Selenium 2 tries to scroll to the element and then click on it. This is because Selenium 2 will not interact with an element unless it thinks that it is visible.

Be aware that scrollIntoView is not a selenium method is a DOM method  and only scrolls the element into view. If scrollIntoView cannot scroll the element into view, it will just fail silently

Before to take the scrollIntoView approach I was trying moveToElement but I figgured out I have more control on how the element is scrolled with scrollIntoView than with moveToElement.

Selenium is only  bringing the element into view so that the mouse can be placed on it. It does not give you any say in how it is going to do it so you might end up with element is not clickable exception raised. scrollIntoView however allows you to specify whether you want the top or bottom of the element to be align with its scrollable ancestor.

Usage:

executeScript("arguments[0].scrollIntoView();",element)

movetoElement

The Selenese moveToElement does two things:

  1. it scrolls the element into view
  2. moves the mouse on top of the element.

You can read more about scrollintoview on the mozilla documentation here.

So what to choose?

First Im going with the moveToElement because I want as much as I can to keep the user interaction as native as possible. Also there are cases where selenium commands are not possible or very expensive ( each selenium command is a trip to the server) , so in these cases I’m going to the executescript.

Happy Testing!


Like it? Share with your friends!

646
1 comment, 646 points

What's Your Reaction?

cute cute
0
cute
scary scary
0
scary
wtf wtf
0
wtf
geek geek
1
geek
WIN WIN
1
WIN
Love Love
0
Love
OMG OMG
0
OMG
Angry Angry
0
Angry
Lol Lol
0
Lol
Test engineer

One Comment

Your email address will not be published. Required fields are marked *

Choose A Format
Trivia quiz
Story