One potential approach to consider is a versatile method that:
- is not limited to a specific CSS3 selector
- can replicate jQuery's pre-built animations like
slideDown()
or fadeIn()
.
If this method (let's name it .css3Animate()
) needs to function in all of the following scenarios:
// method-chain
$('#my_object').css3Animate('animate_scale').fadeOut(1000);
// callback
$('#my_object').css3Animate('animate_scale', function() {
$(this).fadeOut(1000);
});
// .promise().then()
$('#my_object').css3Animate('animate_scale').promise().then(function() {
$(this).fadeOut(1000);
});
A particular jQuery plugin accomplishes these objectives...
(function($) {
var aniend = 'webkitAnimationEnd oanimationend msAnimationEnd animationend';
$.fn.css3Anim = function(cssClass, callback) {
var $this = this; // In the context of a plugin, `this` already represents a jQuery collection.
return this.queue(function(next) { // Add the CSS animation to the elements' fx queue.
$this.queue(function(){}) // Halt the animation queue during the CSS transition.
.one(aniend, function() {
if(callback && typeof callback === 'function') {
callback.call(this);
}
$this.removeClass(cssClass) // Ready for another call
.dequeue(); // Permit the fx animation queue to advance and fulfill the associated promise.
})
.addClass(cssClass); // Trigger the essential animation
next(); // Move on to the queue blockage indicated above.
});
};
})(jQuery);
http://jsfiddle.net/sy51tyn5/1/
The behavior is satisfactory but not flawless. The plugin is meant to handle queuing two or more animations, yet it struggles with three or more.
In the demonstration, you'll notice that buttons are disabled while an animation is ongoing, preventing interference while the CSS3 animation plays out. If you uncheck the checkbox and repeatedly click the buttons, you'll easily disrupt the process.
This issue might stem from the unpredictability of next()
's progression to the queue blocker - external factors may intervene. Further investigation is required to address this. Perhaps someone adept could provide insight?