June 17, 2011 2

Triggering CSS3 Animations from Javascript


I seem to be getting a lot of traffic lately from Google from people interested in triggering CSS3 Animations from Javascript. Its actually really trivial and no different to manipulating another other style property, so here’s a quick how to.

There are a number of properties an animation can have but the bare minimum are:

It’s likely you’ll also be interested in:

  • Easing Function: animationTimingFunction (defaults to ‘ease’) more info

For a full list of animation properties see the MDC Docs.

So assuming you have an animation defined called boxRotate, you could just do the following:

var elem = document.getElementById('test');

elem.style.WebkitDuration = '2000ms';
elem.style.WebkitAnimationName = 'boxRotate';

This would apply the boxRotate animation to the element with ID #test, lasting 2 seconds with the default ease timing function.

I’ve wrapped some of this functionality up in my CSSAnimationKeyframeEvents shim, which was built to produce the missing events for each animation keyframe but can also be used to easily trigger an animation from Javascript. It also has the added bonus of supporting more vendor strings than just WebKit. Whilst WebKit based browsers are currently the only ones to support CSS animations, this will all change with Firefox 5. Using the shim all your CSS animation trigger code will also work with Firefox 5 for free!

Here’s the same example using the shim (and the provided jQuery plugin):

$('#test').cssanimation('boxRotate', 2000);

Whilst this is useful I was also inspired by a discussion with Divya Manian to write a simple Javascript parser for the animation shorthand syntax. This (once it’s complete) will allow for much more complex requests using the standard CSS3 syntax, for example:

$('#test').cssanimation('boxRotate 2000ms linear 1s 5');

A work in progress version of the parsing code can be found on GitHub’s Gist, feel free to test it out and update it if you find any bugs. Once I’m more convinced its stable I’ll roll it into the main codebase. There is also a demo of the code in action available on jsbin.

  • Robert

    I’ve been working on a cross-browser solution for CSS3 animation and transitions. Only starting with a proof of concept, and it’s very crude right now. https://github.com/americanyak/transie Fork it if you want and give feedback…I’m assuming I’ll probably try and fork your github event testing into the project at some point.

  • http://www.joelambert.co.uk Joe Lambert

    Hi Robert, thanks for the comment.

    Will keep an eye on the repo and give it a proper look once its a bit more mature.  Feel free to borrow code, its all under MIT so as long as its accredited you can do as you please with it :)