Created
April 4, 2012 10:45
-
-
Save mataspetrikas/2300296 to your computer and use it in GitHub Desktop.
Check if the DOM node is visible in the 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 elementInViewport(el) { | |
var rect = el.getBoundingClientRect() | |
return rect.top < (window.innerHeight || document.body.clientHeight) && rect.left < (window.innerWidth || document.body.clientWidth); | |
} | |
// and then you can use it: | |
alert(elementInViewport(document.getElementById('inner'))); | |
// or | |
alert(elementInViewport($('#inner')[0])); | |
` |
Try this:
return rect.bottom > 0 &&
rect.right > 0 &&
rect.left < (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */ &&
rect.top < (window.innerHeight || document.documentElement.clientHeight) /*or $(window).height() */;
Both previous solutions have the algebra wrong. Think about it, the top of an element can be above the top of viewport, but if the bottom of the element is showing (i.e. is below the top of the viewport), then it is still visible. Likewise for horizontal calculations.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is the code I use: