Checking if an element is visible on-screen using jQuery
We recently built a little jQuery plugin which allows us to quickly check if an element is within the browsers visual viewport, regardless of the scroll position. If a user can see this element, the function will return true.
?The visual viewport is the part of the page that?s currently shown on-screen. The user may scroll to change the part of the page he sees, or zoom to change the size of the visual viewport.? PPK
This method differs from the jQuery :visible selector in that visible checks to see whether the element is hidden using css (basically if offsetWidth or offsetHeight is 0). Our method checks if an element can be seen based on its position relative to the viewport.
In its simplest form, the element can be used as follows:
This method will return true if the entire element is visible (I.e., it will return false if any part of that element is outside the viewport.
Passing true to the ‘visible’ method, will tell the plugin to return true if ANY part of the element is visible on the users screen.
$('#element').visible( true )
The plugin ignores the elements visibility (E.g., display:none; visibility: hidden; offsetWidth or offsetHeight is 0). To filter on css visibility, you can use the jQuery :visible selector:
Currently the plugin only checks for vertical positioning and scroll. We’re planning on adding horizontal support soon, with the ability to optionally run the check on horizontal, vertical or both planes.