Restart CSS3 animations on hover without JavaScript

Spaceship animation restart

Back to the … how to restart CSS3 animations

For a project, I had to find a way to restart CSS3 animations when
hovering over it, but couldn’t use JavaScript.
At first I searched the net if something simple might show up.

But to no avail – everyone proposed you have to use JavaScript for that.
(By the way – if you found the “hack” following before, let me know ;).

So I studied the W3C’s opinion on the matter and found this sentence:

In order to restart an animation, it must be removed then reapplied.

Which made me think about how to remove an animation without JS.
And again, the W3C had the answer (if you bend your head around the original sentence ;) :

Note that since empty @keyframes rule are valid…

Read and Done, I started with assigning an empty animation on hover:

@keyframes emptyanim {}

#myDIVtoBeAnimated:hover {
    animation:emptyanim;
}

And surprise, surprise, it worked!
The next step was an easy one, why shouldn’t it work with no defined keyframe at all?

Done, tried, works – and even without browsers throwing CSS errors/warnings.

Finally see for yourself in this fiddle of it:

Have fun! :)

0 comments