Is there a callback on completion of a CSS3 animation?

JavascriptCssDom EventsCss Animations

Javascript Problem Overview


Is there any way to implement a callback function in case of css3 animation? In case of Javascript animation its possible but not finding any way to do it in css3.

One way I could see is to execute callback after the animation duration but that doesn't make sure that it will always be called right after the animation ends. It will depend on the browser UI queue. I want a more robust method. Any clue?

Javascript Solutions


Solution 1 - Javascript

Yes, there is. The callback is an event, so you must add an event listener to catch it. This is an example with jQuery:

$("#sun").bind('oanimationend animationend webkitAnimationEnd', function() { 
   alert("fin") 
});

Or pure js:

element.addEventListener("webkitAnimationEnd", callfunction,false);
element.addEventListener("animationend", callfunction,false);
element.addEventListener("oanimationend", callfunction,false);

Live demo: http://jsfiddle.net/W3y7h/

Solution 2 - Javascript

An easy way for you to do a callback that also handles your CSS3 transitions/browser compatibilities would be the jQuery Transit Plugin. Example:

//Pulsing, moving element
$("#element").click( function () {
    $('#element').transition({ opacity: 0, x: '75%' }, function () { $(this).transition({ opacity: 1, x: '0%' }).trigger("click"); });
});

JS Fiddle Demo

Solution 3 - Javascript

If you created the animation with Javascript instead of CSS then you'll want to use the Animation API to set the callback for the animation's onfinish event.

animation = myAnimatedElement.animate([
    {transform: 'translateX(0px)'},
    {transform: 'translateX(-100px)'},
], 700);

animation.onfinish = (e) => {
    // Do something after the animation finishes
};

Worth keeping in mind that if the animation is canceled, removed, or paused then the onfinish event does not fire. You may want to add listeners for those events as well depending on your needs.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalterView Question on Stackoverflow
Solution 1 - JavascriptmethodofactionView Answer on Stackoverflow
Solution 2 - JavascriptGaffView Answer on Stackoverflow
Solution 3 - JavascriptAdam RichardView Answer on Stackoverflow