0

I am trying to scroll to an element using javascript executor on my Ruby script using selenium. However, the script scrolls all the way down of the page and skips the element. Thus not interacting with the element.

Scroll method:

def scroll_into_view(element, locator=nil)
    element = element.nil? ? find(locator) : element
    @wd.execute_script('arguments[0].scrollIntoView(true);', element)
  end

Reference:

scroll_into_view(nil, gear_icon_span_locator)

Do you know of any other ways to scroll to an element in ruby?

I've tried action builders and actually moving to an element, that didn't seem to work.

2
  • I use 'arguments[0].scrollIntoView();' without passing the true parameter and it scrolls right to the element. Have you tried that? Commented Mar 28, 2019 at 18:51
  • Tried it, it is scrolling all the way to the bottom of the page and the element is skipped. Commented Mar 28, 2019 at 18:54

2 Answers 2

0

The script that worked is this, I found the answer from here: Scroll that works for ruby

  def scroll_to_element(element, locator=nil)
    script_string = "var viewPortHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);" +
        "var elementTop = arguments[0].getBoundingClientRect().top;" +
        "window.scrollBy(0, elementTop-(viewPortHeight/2));"
    element = element.nil? ? find(locator) : element
    execute_script(script_string, element)
  end
Sign up to request clarification or add additional context in comments.

3 Comments

Use WATIR which is a wrapper around Ruby Selenium Binding where you can find watir-scroll gem which will help you.
We're not using watir for this project, for different purposes
Okay no problem.
0

In watir you can scroll to element using the below.

element.scroll.to :bottom

5 Comments

It's suppose to scroll to the element bottom.
Not sure why, but it didn't do anything.
Using selenium webdriver 3.13.0 and ruby 2.5.3
Do you have gem 'watir-scroll' in your gemfile? Or did you installed 'watir-scroll' gem?
We're not using watir for this project, for different purposes

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.