jQuery scroll to element

1 min


624
2 comments, 624 points
jQuery scroll to element
jQuery scroll to element

jQuery scroll to element

When you manually test something at the bottom of the page first you need to scroll and second you start interacting with your element , so does selenium. By default selenium actively scrolls to the element that needs to perform actions but you might end up having issues most of them happen on Firefox but even in Google chrome. So in this situation you need a stable method to scroll to the element  and after perform the next selenium action that you want.

I will provide the code in ruby using Capybara but you can easily adapt it to any other programming languages.

 # Scroll to any element/section
    # @param element [Capybara::Node::Element, SitePrism::Section]
    def scroll_to(element)
      element = element.root_element if element.respond_to?(:root_element)
      Capybara.evaluate_script <<-EOS
        function() {
          var element = document.evaluate('#{element.path}', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
          window.scrollTo(0, element.getBoundingClientRect().top + pageYOffset - 200);
        }();
      EOS
    end
So what is a root_element?

The css selector that is passed as the 3rd argument to the sections method (“#results li”) is used to find a number of capybara elements. Each capybara element found using the css selector is used to create a new instance of the SearchResultSection and becomes its root element. So if the css selector finds 3 li elements, ccallingsearch_results will return an array containing 3 instances of SearchResultSection, each with one of the lielements as it’s root element.

If you are wandering about root_element , you can consult site prism git hub page for more details .

You can enjoy reading a pair of  articles part of the selenium tips bunch:  Capybara get attribute or Tellurium selenium .

Happy testing people!


Like it? Share with your friends!

624
2 comments, 624 points

What's Your Reaction?

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

2 Comments

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

Choose A Format
Trivia quiz
Story