Jump to content
Search Community

Play and reverse animation by clicking on same element

Mike H D test
Moderator Tag

Go to solution Solved by Carl,

Recommended Posts

Hi,

My first time playing with GSAP, and it is going great so far. I am animating a card flip on click, this is my code at the moment:

 

gsap.utils.toArray(".card-wrapper").forEach(function(card) {
      gsap.set(card, {
        transformStyle: "preserve-3d",
        transformPerspective: 1000
      });
      const q = gsap.utils.selector(card);
      const front = q(".front");
      const back = q(".back");
      
      gsap.set(back, { rotationY:-180 });
      
      const tl = gsap.timeline({ paused: true })
        .to(front, { duration: 1, rotationY: 180 })
        .to(back, { duration: 1, rotationY: 0, rotationZ: "random(-6, 6)" }, 0)
        .to(card, { z: 50 }, 0)
        .to(card, { z: 0 }, 0.5);
      card.addEventListener("click", function() {
        tl.reversed() ? tl.play() : tl.reverse();
      });
    });

 

Which is nearly working perfectly. The only issue is I need to click twice initially to run the animation for the first time. After this it works with a single click, running the animation forwards or backwards depending on what is needed.  I guess this has something to do with how I have used the ternary operator in the click listener, but am not sure what to do to fix it. If anyone has any thoughts that would be awesome.

 

Link to comment
Share on other sites

  • Solution

Hi and welcome to the GreenSock forums. 
 

immediately after the last tween in your timeline add

 

tl.reversed(true)

 

or

 

tl.reverse()

 

this way the timeline will be in a reversed state before the first click which means it will play on the first click. 

  • Like 3
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...