Skip to content

Instantly share code, notes, and snippets.

@barkdoll
Created May 9, 2019 19:35
Show Gist options
  • Save barkdoll/44987e9159f642883d709bc9b91921b3 to your computer and use it in GitHub Desktop.
Save barkdoll/44987e9159f642883d709bc9b91921b3 to your computer and use it in GitHub Desktop.
Check if an element is [at least partially] in the browser viewport.
const onScreen = elm => {
const getViewportY = () => {
const top = window.pageYOffset || document.documentElement.scrollTop;
const bottom = top + document.documentElement.clientHeight;
return { top, bottom }
}
const getElmCoordinates = elm => {
const { top, bottom } = elm.getBoundingClientRect();
return { top, bottom }
}
const viewport = getViewportY();
const elmPosition = getElmCoordinates(elm);
const top = elmPosition.top + viewport.top;
const bottom = elmPosition.bottom + viewport.top;
const onScreenFlags = [
(top >= viewport.top && top <= viewport.bottom),
(bottom >= viewport.top && bottom <= viewport.bottom)
];
const atLeastPartlyOnScreen = onScreenFlags.includes(true);
return atLeastPartlyOnScreen;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment