CSS keyframe based JavaScript events

Recently I had to build a combined CSS animation: when first animation is at 5%, the next animation should start. Well, the problem is that the current JS API doesn’t have any events to track css animation keyframe progress (other than start, end and iteration/loop). So, with the newly discovered – by me – requestAnimationFrame, I started to fool around And I ended with a nice Github repo containing the plugin.

Of course, you need a requestAnimationFrame shim. Good, how to use?

CSS keyframes

CSS3 added some kind of custom animation. Instead of having linear animation, you can control various behavior based on animation progress:

.ani {
    -webkit-animation-duration: 2s;
          animation-duration: 2s;
  -webkit-animation-fill-mode: both;
          animation-fill-mode: both;

@-webkit-keyframes foo {
  0% { left:0; }
  25% { left: 150px; }
  100% { left:500px; }

.foo {
  -webkit-animation-name: foo;
  animation-name: foo;

To animate an element, you just need to add both .ani and .foo. Nothing big, right? The script I did detects current keyframe and trigger an event.

JavaScript Events

As I said, JS provides only three events: animationEnd, animationStart and animationIteration (you can read more about this here). you can add an extra keyframe event, just like so:

$('#myElement').live('webkitAnimationEnd webkitAnimationStart keyframe', function(e){
switch( e.type ){
case 'webkitAnimationEnd':
// end event
case 'webkitAnimationStart':
// start event
case 'keyframe':
// trigger event
$('#myElement').keyframe(); // plugin init
$('#myElement').addClass('ani foo'); // css animation
view raw gistfile1.js hosted with ❤ by GitHub

That’s it!


Currently, the script is only detects 5% intervals. So if you need a keyframe at 82%… Good luck!
Also, the script doesn’t always trigger 100% keyframe. But since we already have animationEnd event, this is not a big problem, no? :)

Github repo.


I was lucky enough to need this to work only on chrome. Therefore the demo will only work on chrome. Feel free to fork my gist and improve

Un comentariu to “CSS keyframe based JavaScript events”

Show trackbacks

Ți-a plăcut articolul? Lasă un comentariu!

You can insert code snippets using BBcode:
[js].[/js] [html].[/html] [php].[/php] [css].[/css]
You can also use some HTML tags:
<blockquote>.</blockquote> <code>.</code> <a href="">.</a> <strong>.</strong> <em>.</em>

windows apple dropbox facebook twitter