Skip to content

Instantly share code, notes, and snippets.

@andrit
Created July 10, 2018 16:21
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 andrit/3374d88afe7f6566846b202e9dee15e1 to your computer and use it in GitHub Desktop.
Save andrit/3374d88afe7f6566846b202e9dee15e1 to your computer and use it in GitHub Desktop.

Snippet checking if Element is visible in viewport

Use Element.getBoundingClientRect() and the window.inner(Width|Height) values to determine if a given element is visible in the viewport. Omit the second argument to determine if the element is entirely visible, or specify true to determine if it is partially visible.

const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
  const { top, left, bottom, right } = el.getBoundingClientRect();
  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;
};

e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10}

elementIsVisibleInViewport(el) -> false (not fully visible)
elementIsVisibleInViewport(el, true) -> true (partially visible)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment