6

In the example code below, isIntersecting is always true, probably because the intersecting subject is the parent itself.

Is there a way to use IntersectionObserver to detect the intersection/collision between the two boxes?

The idea was to use this built-in API as the intersection needs to be checked whenever any box position is changed; in the original code, they transition from one position to another and react as soon as a collision is detected. This would be an interesting alternative to polling, for example.

Any ideas would be great.

/** @type {HTMLDivElement[]} */
    const elements = Array.from(document.getElementsByClassName('box'));

    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          console.log(
            `${entry.target.className} is overlapping with another element`
          );
        }
      });
    });
    
    console.log('elements', elements);

    elements.forEach((div) => observer.observe(div));
#container {
  width: 150px;
  height: 150px;
  position: relative;
  background-color: aqua;
}

.box {
  width: 32px;
  height: 32px;
  border: 1px solid #333;
  background-color: yellow;
  position: absolute;
}
<div id="container">
  <div class="box" style="left: 8px; top: 8px;"></div>
  <div class="box" style="left: 48px; top: 48px;"></div>
</div>
Etheryte
  • 24,589
  • 11
  • 71
  • 116
darksoulsong
  • 13,988
  • 14
  • 47
  • 90
  • 2
    As far as I'm aware, `IntersectionObserver` can't be used for this purpose, since it's expressly parent-child as opposed to sibling-sibling. As always, happy to be proved wrong though. I think what might be slightly misleading here is the class name: `VisibilityObserver` might be a more descriptive name, since it's not a universal intersection detection API. – Etheryte Jan 18 '23 at 20:07

0 Answers0