Doing two animations on scroll

I am using JavaScript to have a CSS animation start when the element is in the viewport:

const elements = document.querySelectorAll('.element-one');
const options = {
  root: null,
  rootMargin: '0px',
  threshold: .4
}
const callbacks = (entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting){
      entry.target.classList.add('element-one-animation');
    }
  });
}
let observer = new IntersectionObserver(callbacks, options);
elements.forEach(element => {
  observer.observe(element);
});

This works great. I tried adding a second animation on scroll:

const elements = document.querySelectorAll('.element-two');
const options = {
  root: null,
  rootMargin: '0px',
  threshold: .4
}
const callbacks = (entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting){
      entry.target.classList.add('element-two-animation');
    }
  });
}
let observer = new IntersectionObserver(callbacks, options);
elements.forEach(element => {
  observer.observe(element);
});

But this second one doesn’t work. When I delete the first one, however, the second one does work. I’m not well versed in Javascript and I think it is just something that can’t be repeated but I can’t figure it out. Please help.

>Solution :

The issue you’re facing is related to reusing the same variable names elements, options, and callbacks for both animations. When you declare these variables for the second animation, they overwrite the values of the variables used for the first animation, causing unexpected behavior.

To fix this, you can simply use different variable names for the second animation. Here’s the updated code:

const elementsOne = document.querySelectorAll('.element-one');
const optionsOne = {
  root: null,
  rootMargin: '0px',
  threshold: 0.4
};
const callbacksOne = (entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting){
      entry.target.classList.add('element-one-animation');
    }
  });
};
let observerOne = new IntersectionObserver(callbacksOne, optionsOne);
elementsOne.forEach(element => {
  observerOne.observe(element);
});

const elementsTwo = document.querySelectorAll('.element-two');
const optionsTwo = {
  root: null,
  rootMargin: '0px',
  threshold: 0.4
};
const callbacksTwo = (entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting){
      entry.target.classList.add('element-two-animation');
    }
  });
};
let observerTwo = new IntersectionObserver(callbacksTwo, optionsTwo);
elementsTwo.forEach(element => {
  observerTwo.observe(element);
});

By using distinct variable names (elementsOne, optionsOne, callbacksOne, observerOne for the first animation, and elementsTwo, optionsTwo, callbacksTwo, observerTwo for the second animation), you can ensure that each animation operates independently without interfering with each other.

Leave a Reply