Generic "Animate" function with jQuery
(
Aug 26 2010 - 07:14:32 AM by
Timothy Khouri) - [
print blog
post]
OK, so I needed the ability to animate the "max-height" css property for a project I'm doing at work. We extensively use jQuery in the project, and I know that jQuery has the animate function - so I thought this was going to be a quick answer. I couldn't figure it out, so I figured I'd ask the experts "In jQuery, how do I animate the “max-height” CSS property?"
As it turns out, the animate function expects only a set list of properties that can be animated (such as opacity, height, etc). Max-height is not one of the properties you can animate!
Basically what I needed was the ability to "animate" anything. To be more specific, I needed to be able to specify a 'from' and 'to' value, and have my own callback function executed with the progress along the way. It was an easy method to implement, but I figured I would post it here so that others who may need the same functionality could have it as well.
The jQuery 'animate' function is very awesome, and this function is in no way to replace that.
Quick Example of a Custom jQuery Function
So here goes. First off, to extend jQuery to have your own custom method is fairly simple. Just to illustrate how easy it is to do it, I'll show you a method I came up with a while back, the "outerHTML" method:
(function($) {
$.fn.outerHTML = function() {
return $("<div>").append(this.clone()).html();
};
})(jQuery);
Now, with that method you can do something like this:
alert( $("#some-div").outerHTML() );
Generic Animate jQuery Extension
Now that you understand how to create your own custom jQuery extension, you'll be able to follow along with this code a bit easier. There's not a lot of code, so I'll just paste the entire method and include an explanation in JavaScript comments.
(function ($) {
$.fn.animateX = function animate(from, to, duration, callback) {
if (((to - from) / duration) == 0) {
return;
}
var start = new Date();
this.each(function(i, j) {
var cont = function (s, f, t, d, c) {
var p = ((new Date()) - start) * ((t - f) / d);
if (p != 0) {
var v = f + p;
v = (p > 0)
? ((v < t) ? v : t)
: ((v > t) ? v : t);
callback(v, j);
}
if (v != t) setTimeout(function () { cont(s, f, t, d, c); }, 1);
}
cont(start, from, to, duration, callback);
});
};
})(jQuery);
Here's a demo if you'd like to see an example of what this would do: generic animate with jQuery demo.html
Enjoy!