I'm completely flummoxed by the rootMargin
property of intersection observer.
My goal is to add a class to an element when half it's height has crossed the vertical center of the viewport.
In my current project, nothing I do seems to impact the "root intersection rectangle" and the class is always added immediately. I've tested in latest Chrome and Firefox.
Here's the reduced test case:
// https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
const options = {
root: null, // default, use viewport
rootMargin: '0px 0px -50% 0px',
threshold: 0.5 // half of item height
}
const circle = document.getElementById('circle');
const observerCallback = function(entries, observer) {
console.log('intersected');
circle.classList.add('intersected');
}
window.addEventListener('load', function(event) {
const observer = new IntersectionObserver(observerCallback, options);
observer.observe(circle);
}, false);
.circle {
margin: 100vh auto;
width: 200px;
height: 200px;
background-color: tomato;
border-radius: 50%;
transition: background-color 2s ease-in-out;
}
.circle.intersected {
background-color: mediumseagreen;
}
<div class="circle" id="circle"></div>