Detecting CSS animation and transition end with Javascript

CSS3 animation javascript

Detecting the end of CSS animation and transition with Javascript could be useful if you want to complete some behavior with the DOM modification. In this article I will give you an example of how to use it.

The problem

The common method to detect the ending of an animation is like that:

$('.example').addClass( 'some-class' ).on( 'webkitAnimationEnd mozAnimationEnd oAnimationEnd oanimationend animationend', function() {
    $(this).remove();
});

The problem with the code above is that the callback is not called in IE9. Also it will not be called if the animation is set with 0s duration. To sum it up, it is not safe enough.

The solution
There is a very light library here which provides two functions:

  • onCSSAnimationEnd​ – for animations;
  • CSSTransitionEnd​ – for transitions;

For example:

$('.example').addClass( 'some-class' ).onCSSAnimationEnd( function() {
    $( this ).remove();
});

The same example with vanilla Javascript is like that:

var item = document.querySelector('.example');
item.classList.add('some-class');
item.onCSSAnimationEnd( function() {
    item.parentNode.removeChild( item );
});