A jQuery function to animate using CSS3 transitions if possible, with the built-in animate fallback.

by Richard Bradshaw

This requires you to use the amazing Modernizr library, or could be modified to use your own check for whether the browser supports CSS transitions. It’s rough and ready, but works fine as far as I know!

For lots more info and demos of transitions, have a look at my CSS3 transitions and transforms tutorial.

All this lot goes before your document ready section.

?View Code JAVASCRIPT
var speed = 500; // Default animation speed in milliseconds (1000 = 1 second)
 
var vP = "";
var transitionEnd = "TransitionEnd";
if ($.browser.webkit) {
	vP = "-webkit-";
	transitionEnd = "webkitTransitionEnd";
} else if ($.browser.msie) {
	vP = "-ms-";
} else if ($.browser.mozilla) {
	vP = "-moz-";
	transitionEnd = "transitionend";
} else if ($.browser.opera) {
	vP = "-o-";
	transitionEnd = "oTransitionEnd";
}
 
function animate2(object, cssProperties, callback, ms) {
	if (!ms) {
		ms = speed;
	}
 
	if (Modernizr.csstransitions) {
		object.css(vP+"transition", "all "+ms+"ms ease-in-out");
 
		object.css(cssProperties);
 
		if ($.isFunction(callback)) {
			object.bind(transitionEnd,function(){
			     object.unbind(transitionEnd);
			     callback();
			});
		}
 
	} else {
		if ($.isFunction(callback)) {		
			object.animate(cssProperties, ms, callback);
		} else {
			object.animate(cssProperties, ms);			
		}
	}
}

Then, the bit that runs once the DOM is built:

?View Code JAVASCRIPT
$(function(){
    // Simplest example. Animate the height of a box to 600px high.
    animate2($("#my_box"), {"height": 600});
 
    // More complex. Animate the height to 600px, and the left-margin to 100px with a callback.
    animate2($("#my_box"), {"height": 600, "margin-left": 10px}, function(){
         console.log("Animation finished");
    }, 1500);
 
});

Rather pleasant I feel. I’d really welcome suggestions for improvement, the idea is to provide a simple way to move things around using the best method possible.

Random Posts