Skip to content

Instantly share code, notes, and snippets.

@WebDevLuke
Created April 1, 2019 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebDevLuke/fe5e6019f4ce94ff37e402f63cc5eea2 to your computer and use it in GitHub Desktop.
Save WebDevLuke/fe5e6019f4ce94ff37e402f63cc5eea2 to your computer and use it in GitHub Desktop.
Old fashioned method of checking if an element is within the viewport.
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)
);
};
@devzom
Copy link

devzom commented Nov 18, 2022

Nice one!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment