Suraj Radhakrishnan
Suraj Radhakrishnan

Reputation: 67

How to reverse gsap timeline on mouseleave event?

I'm trying to make a card hover animation with GSAP.

I created a function cardAnim that returns a card timeline cardAnimTl. On mouseenter the timeline is played cardAnimTl.play(). I want to reverse the timeline on mouseleave. I tried cardAnimTl.reverse() but it doesn't work.

Here's the link to the code on codepen.

It plays but it doesn't reverse. Any suggestions? Thanks.

Upvotes: 1

Views: 469

Answers (1)

Zach Saucier
Zach Saucier

Reputation: 25984

You are calling the function in both the enter and leave event. That means that you're creating and returning the animation each time one of those events happens.

What you want to do instead is create the timeline once then use control methods on that timeline.

cards.forEach((card) => {
  const cardCover = card.querySelector(".card__cover");
  const anim = cardAnim(cardCover);
  
  card.addEventListener("mouseenter", () => anim.play());
  card.addEventListener("mouseleave", () => anim.reverse());
});

Demo. I write more extensively about this subject in my article on animating efficiently.

FYI: You're more likely to get a faster answer over on the GreenSock forums.

Upvotes: 3

Related Questions