Skip to content

Why IntersectionObserver is not applying the classes?

I’m following a tutorial about IntersectionObserver, but I can’t seem to get it to work… I’m trying to apply an animation on the elements that are visible in the viewport. I will paste the JS code here and the full example with html and css is here: https://codepen.io/cucurutcho/pen/KKWRrov

    const images = document.querySelectorAll('.anim');

    console.log("I'm working!");

    observer = new IntersectionObserver((entries) => {

        entries.forEach(entry => {
          console.log("I'm working 2!");
            if(entry.intersectionRatio > 0) {
                entry.target.style.animation = `fadeInUp animated animatedFadeInUp`;
            }
            else {
                entry.target.style.animation = 'none';
            }
        })

    })

    images.forEach(image => {
      console.log("I'm working 3!")
        observer.observe(image)
    })

    

Any help is greatly appreciated! Thanks so much guys

Answer

You’re not targeting the classes, you’re overwriting the text content of the CSS animation property as described here.

You need classList instead:

if (entry.intersectionRatio > 0) {
  entry.target.classList.add("fadeInUp", "animated", "animatedFadeInUp")
} else {
  entry.target.classList.remove("fadeInUp", "animated", "animatedFadeInUp")
}