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></div> <div> <img src="./card-1.png" alt=""> </div> <div> <img 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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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.

You Might Also Like