0

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

DisplayName
  • 125
  • 1
  • 16

1 Answers1

1

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")
}
lawrence-witt
  • 8,094
  • 3
  • 13
  • 32
  • Thanks for your suggestion @lawrence-witt, I tried using that, but also doesn't apply the classes? Maybe there's something wrong somewhere else in the code – DisplayName Jun 17 '21 at 15:47
  • Plug it into your codepen in place of the previous conditional and it works. Not much more to add here. – lawrence-witt Jun 17 '21 at 16:04
  • It did work indeed @lawrence-witt, in my local machine it wasn't and I got it resolved when I moved the JS load to the end of the body, instead of being in the head! Thanks so much again for your help sir – DisplayName Jun 17 '21 at 18:30