Skip to content

Instantly share code, notes, and snippets.

@chrisyip
Created August 23, 2016 08:42
Show Gist options
  • Save chrisyip/e4a1f7874144cd2faca2dd86f94bfe25 to your computer and use it in GitHub Desktop.
Save chrisyip/e4a1f7874144cd2faca2dd86f94bfe25 to your computer and use it in GitHub Desktop.
/**
* 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