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:
<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>
.container{
height: 100vh;
}
gsap.to('.image' ,{
x:500,
rotation:250,
duration:1,
opacity:1,
scrollTrigger:{
trigger:'.image',
start:'top center',
toggleActions:'restart none none none',
}
})
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.