So, I've got this -webkit-animation
rule:
@-webkit-keyframes shake {
0% {
left: 0;
}
25% {
left: 12px;
}
50% {
left: 0;
}
75% {
left: -12px;
}
100% {
left:0;
}
}
And some CSS defining some of the animation rules on my box
:
#box{
-webkit-animation-duration: .02s;
-webkit-animation-iteration-count: 10;
-webkit-animation-timing-function: linear;
}
I can shake
the #box
like this:
document.getElementById("box").style.webkitAnimationName = "shake";
But I can't shake it again later.
This only shakes the box once:
someElem.onclick = function(){
document.getElementById("box").style.webkitAnimationName = "shake";
}
How can I re-trigger a CSS animation via JavaScript without using timeouts or multiple animations?
Clone works pretty good on paused Karaoke: On IE11 had to force a reflow (R. Krupiński's shorter version).
or you can use the following:
Is there an issue with using
setTimeout()
to remove the class and then read it 5ms later?Following the suggestion from https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Tips, remove and then add the animation class, using requestAnimationFrame to ensure that the rendering engine processes both changes. I think this is cleaner than using setTimeout, and handles replaying an animation before the previous play has completed.
});
http://jsfiddle.net/gcmwyr14/5/
Reset the value first. Use reflow to apply the change without using timeout:
In contrast to the accepted answer that recommends
animationEnd
, this method resets the animation even when it's still in progress. This might be or might be not what you want.An alternative would be to create a duplicate
@keyframes
animation and switch between the two:You have to first remove the animation, then add it again. Eg:
To do this without setTimeout remove the animation during
onmousedown
, and add it duringonclick
:A simple but effective alternative:
HTML:
css:
jQuery:
Demo:
http://jsfiddle.net/5832R/2/
Issues:
I don't know if it works on Firefox, because the animation doesn't seem to work there...