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>