Joe Lambert More details on blog Follow joelambert on Twitter
click me

Keyframe Events for CSS3 Animations

CSS3 Animations are great but the current implementation doesn't trigger Javascript Events for each Keyframe (see here for more information).

The CSSAnimation object provides the events the browser vendors left out! This allows you to bind event handlers to cssAnimationKeyframe events and perform any additional code that needs to happen at each keyframe.

Note: This won't work as well on Mobile Webkit until webkitRequestAnimationFrame() is implemented!

Demo

In the example above, the text in the center of the box is updated when each keyframe is triggered.

CSS - Defining the Animation

@-webkit-keyframes boxrotate {
  0% {
    -webkit-transform: translate3d(0, 0, 0);
    background: #da371e;
  }

  25% {
    -webkit-transform: translate3d(0px, 200px, 0) rotate(90deg);
    background: #da3ab9;
  }

  50% {
    -webkit-transform: translate3d(200px, 200px, 0) rotate(180deg);
    background: #34b6da;
  }

  75% {
    -webkit-transform: translate3d(200px, 0, 0) rotate(270deg);
    background: #88da50;
  }

  100% {
    -webkit-transform: translate3d(0, 0, 0) rotate(360deg);
    background: #da371e;
  }
}

Javascript - Triggering the Animation

$('#container').click(function(event) {
	$('#animate').cssanimation('boxrotate', 3000);
})

Javascript - Listening for Events

$('#animate').bind('cssAnimationKeyframe', function(event){
	switch(event.originalEvent.keyText) {
		case '0%':
			/* Do Something... */ 
			break;
		case '25%':
			/* Do Something... */ 
			break;
		case '50%':
			/* Do Something... */ 
			break;
		case '75%':
			/* Do Something... */ 
			break;
		case '100%':
			/* Do Something... */ 
			break;
	};
});
Source & Docs @ Github