Is there an efficient way to tell if a DOM element (in an HTML document) is currently visible (appears in the viewport)?
(The question regards Firefox)
Is there an efficient way to tell if a DOM element (in an HTML document) is currently visible (appears in the viewport)?
(The question regards Firefox)
Depends what you mean by visible. If you mean is it currently shown on the page, given the scroll position, you can calculate it based on the elements y offset and the current scroll position.
I found it troubling that there wasn't a
jQuery
centric version of the functionality available. When i came across Dan's solution i spied the opportunity to provide something for folks who like to program in thejQuery
OO style. Be sure to scroll up and leave an upvote on Dan's code. Its nice and snappy and works like a charm for me.bada bing bada boom
usage
Update: Time marches on and so have our browsers. This technique is no longer recommended and you should use @Dan's solution below (https://stackoverflow.com/a/7557433/5628) if you do not need to support IE<7.
Original solution (now outdated):
This will check if the element is entirely visible in the current viewport:
You could modify this simply to determine if any part of the element is visible in the viewport:
I tried Dan's answer however the algebra used to determine the bounds means that the element must be both ≤ the viewport size and completely inside the viewport to get
true
, easily leading to false negatives. If you want to determine whether an element is in the viewport at all, ryanve's answer is close but the element being tested should overlap the viewport, so try this:Based on @dan's solution above (https://stackoverflow.com/a/7557433/5628), I had a go at cleaning up implementation so that using it multiple times on the same page is easier:
I think this is a more functional way to do it. The Dan's answer do not work in recursive context.
This function solve the problem when your element is inside others scrollable divs by testing any levels recursively upper to the HTML tag, and stops in the first false.