Created
February 2, 2016 20:54
-
-
Save ellm/c9161120e6fdbf10e00f to your computer and use it in GitHub Desktop.
JavaScript - Test for Element in 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
// Check to see if an element is in the viewport | |
function elementInViewport(el) { | |
var top = el.offsetTop; | |
var left = el.offsetLeft; | |
var width = el.offsetWidth; | |
var 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) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment