// Next we want to create a function that will be called when that element is intersected
function handleIntersection(entries) {
// The callback will return an array of entries, even if you are only observing a single item
entries.map((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add('visible')
} else {
entry.target.classList.remove('visible')
}
});
}
Weare picking the part of the HTML that needs to be animated.
This is the callback function, which does the DOM manipulation.
This is the new observer created.
This renders the final output, which is desired. Althoug I understand the causation inside the code, but still have some difficulty in analysing the last part of the code. Thank you so much.
No, this scopes the observer to tell it to watch for its specific type (intersection) in relation to the target.
When it has an observation to report, it calls the handler (handleIntersection in this case) to deal with whatever it has observed.
It is the handler that actually causes the object to animate by nature of applying a class to the element, which causes a CSS animation to play out (as defined by the CSS of the demo).
I think that a useful way to think of the IntersectionObserver is that it behaves similar to an event handler, such as the mouseEnter or mouseLeave event. In the case of intersections, it’s triggering an event when the element enters or leaves the screen.
Thank you so much. There is a constant pattern in using this API.
Two steps:
const observer = new IntersectionObserver();
observer.observe(section);
The first one creates a new object from that API, and if my understanding is correct then
the 2nd one gives the instruction to that object that which part of the DOM to intersect/monitor/implement change, in terms of visibility of that element.
There is one more example here →
This part →
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
const id = entry.target.getAttribute('id');
if (entry.intersectionRatio > 0) {
document.querySelector(`nav li a[href="#${id}"]`).parentElement.classList.add('active');
} else {
document.querySelector(`nav li a[href="#${id}"]`).parentElement.classList.remove('active');
}
});
});
And this is #2:
// Track all sections that have an `id` applied
document.querySelectorAll('section[id]').forEach((section) => {
observer.observe(section);
});