Detecting the end of CSS animation and transition could be useful if you want to back up some of your JavaScript behavior on CSS. The most common uses of this in my practice are:

Animating the display: none . I used the technique on Readerrr for tabbed content and modal boxes: the new content or modal box shows up only after the old one disappears. And…

Animating the disappearance of an element and then removing it from the DOM. I did this here on the cart of my shop.

Problem

Let’s take the shopping cart case as an example. Usually, I remove an item from the cart in this way:

$( '.item' ).addClass( 'disappear' ).on( 'webkitAnimationEnd mozAnimationEnd oAnimationEnd oanimationend animationend', function() { $( this ).remove(); });

The problem with the code above is that it does not degrade gracefully: the callback would not be fired if the browser (i.e. IE 9-) did not support CSS animations. Also, the callback wouldn’t be fired if for some reason the duration of an animation was set to 0s . To sum it up, using this code is not safe enough.

Solution

In order to avoid these flaws, you can use these tiny helper functions I wrote:

onCSSAnimationEnd ​ – for animations ;

​ – for ; CSSTransitionEnd​ – for transitions;

Using them is that simple:

$( '.item' ).addClass( 'disappear' ).onCSSAnimationEnd( function() { $( this ).remove(); });

There is a version of no-dependencies JavaScript code for your service:

var item = document.querySelector( '.item' ); item.classList.add( 'disappear' ); item.onCSSAnimationEnd( function() { item.parentNode.removeChild( item ); });

The source of both functions are available for download:

oncssanimationend.js ; no dependencies (IE 9+);

360 bytes bytes when minified and gzipped;

; no dependencies (IE 9+); 360 bytes bytes when minified and gzipped; jquery.oncssanimationend.js; jQuery dependency (compatible with v1 and v2);

322 bytes when minified and gzipped;

Finally, check out the demo page to see the functions in action and inspect the source code for implementation on your next project:

Demo