Created
August 23, 2016 08:42
-
-
Save chrisyip/e4a1f7874144cd2faca2dd86f94bfe25 to your computer and use it in GitHub Desktop.
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
/** | |
* Detect if element is in view | |
* | |
* @method isElementInView | |
* @param {HTMLElement} element the target element | |
* @param {HTMLElement} [parentElement] container element, default is widnow | |
* @param {Boolean} [ignoreBottom] useful when element is taller than container | |
* @return {Boolean} element is in view or not | |
*/ | |
function isElementInView (element, parentElement, ignoreBottom) { | |
if (element instanceof HTMLElement === false) { | |
return false | |
} | |
const rect = element.getBoundingClientRect() | |
if (parentElement instanceof HTMLElement) { | |
const parentRect = parentElement.getBoundingClientRect() | |
const topInView = rect.top >= parentRect.top && | |
rect.top < parentRect.bottom && | |
rect.left >= parentRect.left && | |
rect.left < parentRect.right | |
if (ignoreBottom) { | |
return topInView | |
} | |
return topInView && | |
rect.bottom <= parentRect.bottom && | |
rect.right <= parentRect.right | |
} | |
const topInView = rect.top >= 0 && rect.left >= 0 && | |
rect.top < window.innerHeight && | |
rect.left < window.innerWidth | |
if (ignoreBottom) { | |
return topInView | |
} | |
return topInView && | |
rect.bottom <= window.innerHeight && | |
rect.right <= window.innerWidth | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment