Skip to content

Instantly share code, notes, and snippets.

@mrosati84
Created December 20, 2012 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrosati84/4346530 to your computer and use it in GitHub Desktop.
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
(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));
@wutupake
Copy link

Nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment