check if an element is visible in the viewport in javascript

Here is a way to check if an element is currently visible in the viewport using JavaScript:

index.tsx
function isElementInViewport(el) {
  // Get element's position and size
  var rect = el.getBoundingClientRect();

  // Check if element is fully visible
  return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  );
}

// Example usage:
var myElement = document.getElementById('my-element');

if (isElementInViewport(myElement)) {
  console.log('Element is fully visible in the viewport');
} else {
  console.log('Element is not fully visible in the viewport');
}
622 chars
22 lines

This method uses the getBoundingClientRect() method to get the position and size of the element relative to the viewport. It then checks if the element is fully visible in the viewport by comparing its top, left, bottom, and right coordinates with the viewport's dimensions.

Alternatively, you can use the Intersection Observer API to detect when an element enters or exits the viewport. This method is usually more performant, especially for detecting changes in the element's visibility over time. Here is an example:

index.tsx
var observer = new IntersectionObserver(function(entries) {
  entries.forEach(function(entry) {
    if (entry.intersectionRatio > 0) {
      console.log('Element is fully visible in the viewport');
    } else {
      console.log('Element is not fully visible in the viewport');
    }
  });
});

var myElement = document.getElementById('my-element');
observer.observe(myElement);
379 chars
13 lines

This method creates a new IntersectionObserver object and attaches it to the element to observe. When the element intersects with the viewport, the intersectionRatio property of the entry object will be greater than zero. We can use this property to determine if the element is fully visible in the viewport or not.

gistlibby LogSnag