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.Peter-Paul Koch, quirksmode.org
This method differs from the jQuery :visible selector in that the visible plugin 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 checked 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 now supports checking the elements visibility too (E.g., display:none; visibility: hidden; offsetWidth or offsetHeight is 0). To filter on css visibility, you can set the second parameter to true
Horizontal, Vertical and Both, oh my!
The plugin now fully supports both horizontal and vertical scroll positions, with the option of selecting 'both', 'horizontal', or 'vertical' only modes, as follows:
// Check both vertical, and horizontal at once $('#element').visible(true, false, 'both'); // Check only horizontal $('#element').visible(true, false, 'horizontal'); // Check only vertical $('#element').visible(true, false, 'vertical');