The element fires the animationStart and animationStartEnd events when CSS animations are declared.
Is there a way to run a javascript function when:
- All animations are complete, including the animations of the children.
- An animation announcement is not advertised and there is no need to wait.
Here is my current approach: http://codepen.io/miguel-perez/pen/CDcAG
var /** * Fires a custom event when all animations are complete * @param {object} $element - jQuery object that should trigger event * */ triggerAllAnimationEndEvent = function ($element) { var animationCount = 0, animationstart = "animationstart webkitAnimationStart oanimationstart MSAnimationStart", animationend = "animationend webkitAnimationEnd oanimationend MSAnimationEnd", eventname = "allanimationend", unbindHandlers = function(e){ $element.trigger(eventname); // utility.redraw($element); console.log(eventname); }, onAnimationStart = function (e) { if ($(e.target).is($element)) { e.stopPropagation(); animationCount ++; } }, onAnimationEnd = function (e) { if ($(e.target).is($element)) { e.stopPropagation(); animationCount --; if(animationCount === 0) { unbindHandlers(); } } }; $element.on(animationstart, onAnimationStart); $element.on(animationend, onAnimationEnd); }, /** * Fires a custom callback when all animations are finished * @param {object} $element - jQuery object that should trigger event * @param {function} callback - function to run * */ triggerCallback = function ($element, callback) { $element.one("allanimationend", callback); // Fires fake animation events in case no animations are used setTimeout(function(){ $element.trigger("animationstart"); $element.trigger("animationend"); }, 100); // wait a bit }, $elements = $('.element'); $elements.each(function(i){ var $this = $(this); triggerAllAnimationEndEvent($this); triggerCallback($this, function(){ $this.text((i + 1) + " DONE!"); }); });
This approach is limited to setTimeout. When the animation is not declared in the element or when the animation has a delay above the timeout, the call is triggered at the wrong time.
source share