Created
December 20, 2012 16:36
-
-
Save mrosati84/4346530 to your computer and use it in GitHub Desktop.
Simple jQuery plugin that checks if an element is in the visible viewport
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function ($) { | |
if ( typeof $ !== 'function' ) { | |
return false; | |
} | |
$.fn.inViewport = function () { | |
// assign this object to local variable. | |
// use raw DOM node, not jQuery objects. | |
var el = this[0]; | |
// get element offsets | |
var top = el.offsetTop, | |
left = el.offsetLeft, | |
width = el.offsetWidth, | |
height = el.offsetHeight; | |
while ( el.offsetParent ) { | |
el = el.offsetParent; | |
top += el.offsetTop; | |
left += el.offsetLeft; | |
} | |
return ( | |
top >= window.pageYOffset && | |
left >= window.pageXOffset && | |
(top + height) <= (window.pageYOffset + window.innerHeight) && | |
(left + width) <= (window.pageXOffset + window.innerWidth) | |
); | |
}; | |
}(jQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice!