Restarting CSS Animations with JavaScript

It’s old news by now that the second season of House of Cards is out on Netflix, but last night I decided to pay homage to it by animating the title sequence logo in HTML/CSS/JavaScript. You can see a working demo on Codepen.

In the process of creating both a JavaScript and an (almost) pure CSS version of the animation, I learned that restarting CSS animations just doesn’t work quite the way I thought it would. I was attempting to reset both animations on the click of a button, so that you could select whether you wanted to run the CSS or JavaScript version of the animation. The JavaScript version reset itself just fine, but for the life of me I couldn’t reset the CSS animation.

After some soul searching (read: Google), I learned that in order to truly reset an animation, you need to remove the animation from the element and reapply it. That led me to believe that something like the following would work:

$('.flag').removeClass('animation_class').addClass('.animation_class');

That sort of makes sense, right? We remove the class that holds the animation, and then reapply it to the element. Presto, animate-o…right?

Nope. Not Right. Totally off.

Turns out that if we just remove the animation class it doesn’t trigger the animation end event listener on the element. In order to do this, we have a few options. We can clone the element, using JavaScript or we can just use a short setTimeout function to force the animation to restart.

Chris Coyier and Paul Underwood both have good write-ups on restarting CSS animations using a clone, but in my case a short setTimeout function worked just fine.

What I ended up going with was something along the lines of:

$('.flag').removeClass('animation_class');
setTimeout(function() {
    $('.flag').addClass('animation_class');
},1);

The one millisecond delay is enough to restart the animation, but short enough to be completely unnoticeable.

In general I absolutely agree with both Chris and Paul that a setTimeout function isn’t the best solution for restarting CSS animations, but for this small demo it seemed to make more sense than cloning the elements.

If you would like to read up on CSS animations and their events, check out the W3 working draft and the MDN Developer Guide.

1 thought on “Restarting CSS Animations with JavaScript”

  1. resetAnimation(‘divID’,’divClass’);

    function resetAnimation(elm,classname) {
    $(‘#’+elm).removeClass(classname);
    setTimeout(function(){ $(‘#’+elm).addClass(classname); }, 1);
    $(‘#’+elm)[0].offsetWidth = $(‘#’+elm)[0].offsetWidth;
    }

Leave a Reply

Your email address will not be published.