Created
January 14, 2016 14:43
-
-
Save chekit/5b4346248ddd83925c6e to your computer and use it in GitHub Desktop.
Detect if element inside viewport or not
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
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 + window.innerHeight) && | |
left < (window.pageXOffset + window.innerWidth) && | |
(top + height) > window.pageYOffset && | |
(left + width) > window.pageXOffset | |
); | |
} | |
//Source: http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment