April 28, 2012

run/pause CSS animation with jQuery

Question by Ampersand

I would like to start with a paused CSS animation then use jQuery to run the animation for a second before pausing again.

The css is below:

#animation {
  -webkit-animation: one 5s infinite;
  -webkit-animation-play-state: paused;
}

@-webkit-keyframes one {
  0% { .... }
  .....
  100% { .... }
}

It has some complicated keyframes and the aim is that it would play for 1 second to the 20% position then stop.

I tried the jQuery below but it didn’t work:

 $("#click").click(function(){
     $("#animation").css("-webkit-animation-play-state", "running").delay(1000).css("-webkit-animation-play-state", "paused");          
 });

(#click is the div I want to use as the trigger for the animation)

If I remove the delay and subsequent pause it works fine but obviously continues looping.

eg:

 $("#click").click(function(){
     $("#animation").css("-webkit-animation-play-state", "running");            
 });

What would you fine people suggest?

Answer by Starx

jQuery delay() does not function when you are manipulating the css property. Use setTimeOut() instead

$("#click").click(function(){
     $("#animation").css("-webkit-animation-play-state", "running");
     setTimeout(function() { 
       $("#animation").css("-webkit-animation-play-state", "paused");
     }, 1000);
});
...

Please fill the form - I will response as fast as I can!