2

Why can't I repeat a CSS animation with javascript once?

Fiddle: http://jsfiddle.net/6XtSa/

3
  • @TJ It works in Chrome as well I believe, however this is possible in other browsers such as firefox and opera with the -mozzila and -o prefixes respectively, if I recall correctly Commented Apr 24, 2012 at 19:36
  • @BubbaWoop I have delete my comment. You are right and this makes sense, due to Chrome also being powered by the webkit engine. Commented Apr 24, 2012 at 20:21
  • javascript - Restart animation in CSS3: any better way than removing the element? - Stack Overflow Commented Jan 28, 2019 at 2:07

3 Answers 3

6

Here's an example adapted from a deleted answer that suggested using classes. That answer didn't quite get the animation right because it ran infinitely.

The idea is to add the class on click and remove it when the animationend event fires:

@-webkit-keyframes rotate {
    from {
        -webkit-transform: rotate(0deg);
    }
    to {
        -webkit-transform: rotate(360deg);
    }
}

#button.animating {  
    -webkit-animation-name: rotate;  
    -webkit-animation-timing-function: linear;  
    -webkit-animation-duration: 1s; 
}
var btn = document.getElementById('button');

btn.addEventListener('click', function() {
    this.className = 'animating';
});
btn.addEventListener('webkitAnimationEnd', function(){
    this.className = '';
});

http://jsfiddle.net/AndyE/9LYAT/

Sign up to request clarification or add additional context in comments.

2 Comments

Yes I deleted it coz I misunderstood the Q :) I thought he wanted an infinite animation (coffee hasn't kicked in yet :P )
@stecb: I think you were on the right lines. Using classes keeps it neater, IMO.
0

The reason the button is only rotating once is because it's rotating to and not by 360°. It's an absolute value. To rotate again you would have to rotate from 360° to 720°. You may want to have a look at this post: Rotating a Div Element in jQuery and specifically this jsfiddle in one of the answers: http://jsfiddle.net/uLrVy/

1 Comment

How do I then reset, so I don't have to do the animation with javascript?
0

You can try something like this: http://jsfiddle.net/6tZd3/

According to the Safari CSS Visual Effects Guide you can just listen to webkitTranstionEnd event to be notified that the animation has finished. At that point you can reset your animation without animating with JavaScript.

1 Comment

Odd. It works on mine, which is Chrome 15.0.874.121 on Mac OS X. Not sure what might be going on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.