9

Is there any way to know if an element is visible on an html page?

Like this:

enter image description here

One can probably do it considering the horizontal/vertical scrolling positions, the width/height of the browser window and the position/size of the element on the page, but I have little experience in jQuery so I don't know how to do it. And there might be a simple function one can call, I don't know.

dsgriffin
  • 61,907
  • 17
  • 128
  • 134
Alex
  • 4,537
  • 3
  • 33
  • 68
  • possible duplicate of [How to check if an element is in the view of the user with jquery](http://stackoverflow.com/questions/8229291/how-to-check-if-an-element-is-in-the-view-of-the-user-with-jquery) – BenM Mar 29 '13 at 14:07
  • 2
    http://stackoverflow.com/questions/8229291/how-to-check-if-an-element-is-in-the-view-of-the-user-with-jquery. Nicely posed question though. – nickhar Mar 29 '13 at 14:08

2 Answers2

5

You can use the .is(':visible') selectors to check if an element is currently visible in the DOM.

Edit:

However, as @BenM mentioned, this doesn't check if the elements on your page are actually out of your scrollable range - a great little plugin you could use in that case would be Viewport Selectors for jQuery.

dsgriffin
  • 61,907
  • 17
  • 128
  • 134
  • No, you can't. That defines if it is physically displayed in the DOM, not if it's visible to the user on their screen. An element could be visible, but out of scroll range. – BenM Mar 29 '13 at 14:07
1

Here is some code that I use to do this. It has been tested to work great.

function isVisible($obj) {
    var top = $(window).scrollTop();
    var bottom = top + $(window).height();
    var objTop = $obj.offset().top;
    var objBottom = objTop + $obj.height();

    if(objTop < bottom && objBottom > top) {
        //some part of $obj is visible on the screen.
        //does not consider left/right, only vertical.
    }
}
BenMorel
  • 30,280
  • 40
  • 163
  • 285