Jump to content
GreenSock

Search In
  • More options...
Find results that contain...
Find results in...
Vishnu Manda

animation only plays once on click

Recommended Posts

 

I want to animate the background, If click the button background will be animate, It works fine except that after one click, It doesn't work again.

<body>
<div class="loading"></div>
<div class="btn">  <button>CLick</button> </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js "></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.2.6/gsap.min.js "></script>
<script>
    $('button').click(function () {
        ld_gray = gsap.from('.loading', 1,{delay: 0.5, scaleX: 0, transformOrigin: 'left', ease: "expo.out",});
gsap.to('.loading', 1,{ delay: 1.5, scaleX: 0, transformOrigin: 'right', ease: "expo.in",} ); });
</script>
</body>

 

See the Pen dyYLJmq by vishnumanda (@vishnumanda) on CodePen

Link to post
Share on other sites

Hey Vishnu and welcome to the GreenSock forums! 

 

The animations actually are running every time you click but since they are relative tweens, after the first time the value is already at the target so they don't have anywhere else to animate to. 

 

What you should do instead is either 

  1. Create the animation beforehand and control it using control methods in the callback (recommended) or
  2. Use a .fromTo() instead of .from() or .to()

Here's the same thing but using control methods:

const ld_gray = gsap.timeline({paused: true});
ld_gray.from('.loading', {duration: 1, delay: 0.5, scaleX: 0, transformOrigin: 'left', ease: "expo.out",});
ld_gray.to('.loading', {duration: 1, delay: 1.5, scaleX: 0, transformOrigin: 'right', ease: "expo.in",} );

$('button').click(function () {
  ld_gray.restart();
});

I talk more about this and a bunch of other tips in my article on animating efficiently which I highly recommend. 

  • Like 1
  • Thanks 1
Link to post
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.

×