Skip to content

Instantly share code, notes, and snippets.

@AitorAlejandro
Created November 15, 2020 13:29
Show Gist options
  • Save AitorAlejandro/958b984464bf8f978d7450949140ec40 to your computer and use it in GitHub Desktop.
Save AitorAlejandro/958b984464bf8f978d7450949140ec40 to your computer and use it in GitHub Desktop.
How to check if the element specified is visible in the viewport
const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
const { top, left, bottom, right } = el.getBoundingClientRect();
const { innerHeight, innerWidth } = window;
return partiallyVisible
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};
// Examples
elementIsVisibleInViewport(el); // (not fully visible)
elementIsVisibleInViewport(el, true); // (partially visible)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment