I am adding a class when a div gets into the viewport using Intersection Observer. I just can't figure out how to remove the class when the div leaves the viewport. This is what I have so far:
const callback = function (entries) {
entries.forEach(entry => {
if(entry.isIntersecting)
{
entry.target.classList.add('animate1');
observer.unobserve(entry.target)
}
});
}
const observer = new IntersectionObserver(callback);
const targets = document.querySelectorAll('.overlay');
targets.forEach(target => {
observer.observe(target);
})
Thank you for your help Randy. I did get it to work. Here is the final code:
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.intersectionRatio > 0) {
entry.target.classList.add('animate1');
}
else {
entry.target.classList.remove('animate1');
}
})
})
const boxElList = document.querySelectorAll('.overlay');
boxElList.forEach((el) => {
observer.observe(el);
})
instead of this
entries.forEach(entry => {
if (entry.intersectionRatio > 0) {
entry.target.classList.add('animate1');
}
else {
entry.target.classList.remove('animate1');
}
})
you can use toggle() and instead of entry.intersectionRadio > 0 you can use entry.isIntersection
entries.forEach(entry => {
entry.target.classList.toggle("animate1",entry.isIntersection)
})