IntersectionObserver does not seem to work when the observed element has position: absolute and the root is not the
viewport.
Am I missing something here?
(Try removing the position: absolute to see the expected result.)
let intersectionRoot = document.getElementById("intersectionRoot");
let observedElement = document.getElementById("observedElement");
let shifted = false; // Internal for the example
let interSectionObserver = new IntersectionObserver(
(entries, observer) => {
console.log(entries[0].isIntersecting)
},
{ root: intersectionRoot }
);
interSectionObserver.observe(observedElement);
window.setInterval(
() => {
observedElement.classList.toggle("shifted")
},
1000
)
#intersectionRoot {
background-color: red;
width: 100px;
height: 100px;
}
#observedElement {
position: absolute;
background-color: green;
width: 50px;
height: 50px;
}
.shifted {
transform: translate3d(110px, 0, 0)
}
<div id="intersectionRoot">
<div id="observedElement" draggable="true"></div>
</div>
The solution is to add position: relative to the root element. Here's an updated demo.
If you don't explicitly set position: relative to the root element its children (in this case observedElement) refers to the body. From the IntersectionObserver docs: An IntersectionObserver with a non-null root is referred to as an explicit root observer, and it can observe any target Element that is a descendant of the root in the containing block chain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With