Skip to content

Instantly share code, notes, and snippets.

@mscalora
Created December 13, 2019 00:54
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 mscalora/1827a414052101e59d4d58add6dc644b to your computer and use it in GitHub Desktop.
Save mscalora/1827a414052101e59d4d58add6dc644b to your computer and use it in GitHub Desktop.
test if dom element is in viewport either fully or fully/partially/none
function isInViewport (elem, partially) {
let box = elem.getBoundingClientRect(),
top = box.top,
bottom = box.bottom,
right = box.right,
left = box.left,
h = window.innerHeight || document.documentElement.clientHeight,
w = window.innerWidth || document.documentElement.clientWidth,
fully = (top >= 0 && box.left >= 0 && bottom <= h && box.right <= w);
return partially ? fully && 2 || (
((top >= 0 && top < h) ||
(bottom >= 0 && bottom < h) ||
(top < 0 && bottom > h)) &&
((box.left >= 0 && box.left < w) ||
(box.right >= 0 && box.right < w) ||
(box.left < 0 && box.right > w))
) && 1 : fully;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment