Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect element visibility (z-index, fixed, opacity etc) (Intersection Observer V2 alternative)

Intersection Observer V2 will introduce new features to detect actual visibility based on factors such as opacity, z-index and fixed positioning.

Info: https://developers.google.com/web/updates/2019/02/intersectionobserver-v2

Question: is there an alternative or a polyfill to detect actual visibility that works in current browsers?

Test: https://jsfiddle.net/v3kgewhf/

// Intersection Observer V2
const observer = new IntersectionObserver((changes) => {
  for (const change of changes) {
    // ⚠️ Feature detection
    if (typeof change.isVisible === 'undefined') {
      // The browser doesn't support Intersection Observer v2, falling back to v1 behavior.
      change.isVisible = true;
    }
    if (change.isIntersecting && change.isVisible) {
      visibleSince = change.time;
    } else {
      visibleSince = 0;
    }
  }
}, {
  threshold: [1.0],
  // 🆕 Track the actual visibility of the element
  trackVisibility: true,
  // 🆕 Set a minimum delay between notifications
  delay: 100
}));```
like image 441
optimalisatie Avatar asked Nov 16 '22 06:11

optimalisatie


1 Answers

An alternative could be to poll the points at which you are wishing to detect visibility using the DocumentOrShadowRoot.elementFromPoint method with a setInterval delay similar to what you would use as a delay for the Intersection Observer v2.

Here is the caniuse links at this time between the two where elementFromPoint is supported on 99%+ users vs Intersection Observer v2 only supports 69%+.

like image 142
Amber-Williams Avatar answered Dec 04 '22 06:12

Amber-Williams