I am using the IntersectionObserver API.
When a specific section is entered, background-color
is changed.
To handle this, I have to obtain the index of an entered entry in the array of IntersectionObserverEntry
called entries
here.
I used forEach
method to get the index of the entry, but it strangely always set index as 0
. But when I access entry by obtained index, it works well.
const intersectionObserver = new IntersectionObserver(entries => {
entries.forEach((entry,index) => {
if(entry.isIntersecting) {
console.log('Intersecting',index);
entry.target.className = entry.target.className.replace('hidden','fadeIn');
changeBackgroundColor(entry.target.dataset.color);
changeLogoColor(entry.target.dataset.theme);
} else {
console.log('Leave',index);
entry.target.className = entry.target.className.replace('fadeIn','hidden');
}
});
});
const fadeInElemes = document.querySelectorAll('.hidden');
fadeInElemes.forEach((fadeInElem) => intersectionObserver.observe(fadeInElem));
Result is below...
Intersecting 0
Leave 0
Leave 0 .....
What is wrong with my code? Why index is always 0, but access by obtained index results in the right element?
EDIT