Menu

gitpiper

elementIsVisibleInViewport javascript Code Snippet in 2024

browserintermediate

Last Updated: 20 April 2024

Checks if the element specified is visible in the 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(); 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; };
// 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)

javascript snippet similar to elementIsVisibleInViewport For You in April 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️