2

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

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

Tyilo
  • 28,998
  • 40
  • 113
  • 198
  • @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 – Luke Apr 24 '12 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. – T. Junghans Apr 24 '12 at 20:21
  • [javascript - Restart animation in CSS3: any better way than removing the element? - Stack Overflow](https://stackoverflow.com/questions/6268508/restart-animation-in-css3-any-better-way-than-removing-the-element) – user202729 Jan 28 '19 at 02:07

3 Answers3

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/

Andy E
  • 338,112
  • 86
  • 474
  • 445
  • Yes I deleted it coz I misunderstood the Q :) I thought he wanted an infinite animation (coffee hasn't kicked in yet :P ) – stecb Dec 08 '11 at 09:48
  • 1
    @stecb: I think you were on the right lines. Using classes keeps it neater, IMO. – Andy E Dec 08 '11 at 09:55
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/

Community
  • 1
  • 1
T. Junghans
  • 11,385
  • 7
  • 52
  • 75
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.

martineno
  • 2,623
  • 17
  • 14