Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* 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