Last active
June 30, 2019 19:04
-
-
Save vincentorback/9ca8446a4c7c87ce3623 to your computer and use it in GitHub Desktop.
Check if element is 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 if element is in viewport | |
* @param {Node} el | |
* @return {Object} | |
*/ | |
export function elementInViewport(el) { | |
let top = el.offsetTop; | |
let left = el.offsetLeft; | |
let width = el.offsetWidth; | |
let 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 | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment