'Intersection observer - How do you remove a class after leaving the view port

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);
})



Solution 1:[1]

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);
})

Solution 2:[2]

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)
  })
 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Alireza Rezaei