Skip to content

Instantly share code, notes, and snippets.

@sergiodxa
Last active August 29, 2015 14:09
Show Gist options
  • Save sergiodxa/a80b76f9603e2e6f7830 to your computer and use it in GitHub Desktop.
Save sergiodxa/a80b76f9603e2e6f7830 to your computer and use it in GitHub Desktop.
Function to check if a DOM element is in the viewport
/*
@el = DOM element
@full = true | default: false // If true check if any part of the element is in the viewport
*/
function isInViewport (el, full) {
var full = full || false;
// check if the element is a jQuery object
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
if (full) {
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
} else {
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment