I’m not sure what you are asking but you aren’t watching .mol because its a div and you are watching p elements. Change it to a p and it will slide in.
Hi @codeispoetry, the observer callback function doesn’t receive a single entry but an array of entries (which never isIntersecting)… so the check should go like:
function observerCallback (entries) {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.toggle('active')
}
})
}
Well how is the intersection observer supposed to know that? You might still observe() more elements at a later point, which would then require a change in the callback function signature from receiving a single entry to an array of entries…
The same observer can observe more than one element, which may simultaneously cross the given threshold; this is why the callback will always receive an array of entries. I guess you might have implemented it differently so that the callback would get called multiple times with a single element instead, but then you couldn’t bail out from processing the remaining entries as easily.
What you’re running into here is developer knowledge.
You (@codeispoetry) know that there is 1 element on the page that matches, and so you seem to assume the browser also knows. But it does not. It may know once the page is rendered, but maybe there is some javascript somewhere that adds more, or removes the one there was. So the browser cannot rely or there being exactly 1. There is 1 right now, but that is contingent; it didn’t have to be that way. So it certainly can’t call the callback function with a single element, since there are situations possible where there will be either less than one or more one.
Therefore, since the browser can’t reasonably be expected to know how many elements there are or will be, using an array is safest, since it’s easy to represent any amount of elements using an array.
Oh and the mdn has a good example where this would be particularly useful: you might not only be interested in knowing that a certain element changed its intersection status, but how many elements just crossed the threshold.