CSS3 Transitions Callbacks

Comments

CSS3 transitions fire off a TransitionEnd event when they end, so that you can attach a Javascript handler to it. The only (minor) inconvenient is that the event takes different names depending on the platform.

Different event names on different browsers

The events names are ‘transitionend’ (FF), ‘OTransitionEnd’ (Opera), ‘webkitTransitionEnd’ (Webkit). IE9 and lower do not support this, although there are vague promises IE10 will.

The easiest but less elegant approach would be to add event handlers for all of the above cases - in vanilla Javascript:

1
2
3
4
var el = document.querySelector( "..." ); //some element(s)
el.addEventListener( 'webkitTransitionEnd', onTransitionEnd, false );
el.addEventListener( 'transitionend', onTransitionEnd, false );
el.addEventListener( 'OTransitionEnd', onTransitionEnd, false );

Or one can use a sniffer to determine which event name to use

1
2
3
4
5
6
var onTransitionEnd = function ( e ){ alert( 'TRANSITION FINISHED' );}
  , eventName       = document.body.style.webkitBorderRadius?
                        "webkitTransitionEnd":
                        "transitionend"
  ;
el.addEventListener( eventName, onTransitionEnd, false );

In jQuery

1
2
3
4
5
6
var onTransitionEnd = function ( e ){ alert( 'TRANSITION FINISHED' );}
  , eventName       = $.browser.webkit?
                        "webkitTransitionEnd":
                        "transitionend"
  ;
$( document.body ).on( eventName, onTransitionEnd );

Firing the handler after the first event only

The code above will fire off every time the transition ends. If you want it to hapen just the first time, you’ll have to unbind the event handler after you fire it. In jQuery you can just use the method .one instead of .bind, which automatically unbinds itself. With other frameworks, for example dojo, you need to unbind it manually

1
2
3
4
5
6
7
8
9
10
11
var el = dojo.... //some element(s)
  , onTransitionEnd     //callback function
  , eventBinding        //reference to binding
//
onTransitionEnd = function( e ){
  alert( 'TRANSITION FINISHED' );
  dojo.disconnect( eventBinding );
}
//
eventBinding  = dojo.connect( el, 'ontransitionend', onTransitionEnd );
});

Fallback when CSS transitions are not available

Of course we can’t just ignore IE - they are (still!) the most used web browser out there. My preferred strategy is to use modernizr as a sniffer, and fallback on your framework’s animation methods if not supported.

1
2
3
4
5
if( Modernizr.csstransitions ) {
  //use them if available
} else {
  //use your preferred js animation functions
}

Comments