More Than One Elements with Same Class Gsap

More Than One Elements with Same Class Gsap

I'm working on GSAP and I have two elements on different pages that have the same class and I want to apply their animation using scrollTrigger when I reach the element. Is there a way I can do this with a function instead of giving them a specific class and repeating myself?

Here is my code:

HTML:

 <div class="container"></div>
    <div class="containe">
        <img class="image" src="./card-1.png" alt="">
    </div>
    <div class="container">
        <img class="image" src="./card-2.png" alt="">
    </div>

CSS:

.container{
 height: 100vh;
}

GSAP:

gsap.to('.image' ,{
    x:500,
    rotation:250,
    duration:1,
    opacity:1,
    scrollTrigger:{
        trigger:'.image',
        start:'top center',
        toggleActions:'restart none none none',
    }
})

1 Answer

I believe you don't need to repeat the code for the same class; just put GSAP javascript in a single js file and call it anywhere you want. Also, you can use the same class on a single page and scroll trigger them separately:

1. By using toArray() method:

var sections = gsap.utils.toArray(".image");

sections.forEach((section) => {
  gsap.to(section, {
    x: 500,
    rotation: 250,
    duration: 1,
    opacity: 1,
    scrollTrigger: {
      trigger: section,
      end: "-=500",
      scrub: true,
      toggleActions: "restart none none none",
    },
  });
});

tweak start / end points for best result. Example Pen

2. you can also use ScrollTrigger.batch

ScrollTrigger.batch(".image", {
  onEnter: (batch) =>
    gsap.to(batch, {
      x: 500,
      rotation: 250,
      duration: 1,
      opacity: 1,
    }),
});

You can also set onLeave animation. Checkout this Pen for example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.