Created
April 1, 2019 10:06
-
-
Save WebDevLuke/fe5e6019f4ce94ff37e402f63cc5eea2 to your computer and use it in GitHub Desktop.
Old fashioned method of checking if an element is within the 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
export default function inViewport(elem, options = {}) { | |
const props = { | |
offsetBefore: typeof options.offset === 'object' ? -Math.abs(options.offset.before) : -Math.abs(options.offset) || 0, | |
offsetAfter: typeof options.offset === 'object' ? options.offset.after : 0, | |
threshold: options.threshold || 0 | |
} | |
const bounding = elem.getBoundingClientRect(); | |
const bottom = () => { | |
if(!props.threshold) { | |
return (bounding.bottom + props.offsetBefore) - elem.offsetHeight; | |
} | |
else { | |
return ((bounding.bottom + props.offsetBefore) - elem.offsetHeight) + (elem.offsetHeight * (props.threshold / 100)) | |
} | |
}; | |
const top = () => { | |
let unit = options.threshold === 0 ? -Math.abs(elem.offsetHeight) : -Math.abs(elem.offsetHeight * (options.threshold / 100) + elem.offsetHeight); | |
return (bounding.top + props.offsetAfter) - elem.offsetHeight >= unit | |
}; | |
return ( | |
top() && | |
bounding.left >= 0 && | |
bottom() <= (window.innerHeight || document.documentElement.clientHeight) && | |
bounding.right <= (window.innerWidth || document.documentElement.clientWidth) | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice one!