Last active
August 29, 2015 14:09
-
-
Save sergiodxa/a80b76f9603e2e6f7830 to your computer and use it in GitHub Desktop.
Function to check if a DOM element is in the viewport
This file contains 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
/* | |
@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