RSSAmplifier

Osvaldas Valutis blog · Jun 23, 2015

Detecting CSS Animation and Transition End with JavaScript

0
Sign in to vote or save

Osvaldas Valutis

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;
  • 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:

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

See the demo

Read the original on osvaldas.info

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.