chasethesunnn
chasethesunnn

Reputation: 2234

How to detect element is present within viewport? (Capybara, ruby)

I have a step that checks for the footer visibility here

And (/^the footer appears$/) do
   within("div.footer") do
      assert_selector "a", :text=> "About"
      ...
   end
end

Basically I load the page and scroll to the bottom then do this check, but I also noticed that this steps works without me having to scroll to the bottom. I did some testing and found out this step only checks for visibility on the entire page. It doesn't check for visibility within the viewport.

I want to have a check that passes only when the element is within the viewport. Is this possible without Rspec and just capybara/ruby/js alone?

Upvotes: 3

Views: 1661

Answers (1)

Thomas Walpole
Thomas Walpole

Reputation: 49950

You can use #evaluate_javascript to check this. Something along the lines of

in_view = evaluate_script("(function(el) {
  var rect = el.getBoundingClientRect();
  return (
    rect.top >= 0 && rect.left >= 0 &&
    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  )
})(arguments[0]);", find('div.footer'))
# assert that in_view is true, or whatever you want.

Upvotes: 4

Related Questions