06/29/2009
Synchronizing jQuery Animations
Posted by
Matthew Quinn
On a current project I had to animate the "opening" of an absolute-positioned div (initially hidden) from the top-right to its full dimensions (917x228). That means animating the width (from 0px to 917px), the offset left (from its initial value to 917px less than that) and the height (from 0px to 228px).
The first thing that comes to mind is the following jQuery animation function (assuming initial height and width 0px):
$("#TheElement").animate({
width: "917px",
height: "228px",
left: "-=917px"
});
However, these 3 animations are not synchronized - deviations in the speed at which they run may put the "width" and "left" out of whack, which completely ruins the effect as the div jumps around horizontally during the animation. This was especially noticeable in Firefox. As it turns out, jQuery lets you set a (mostly undocumented) callback on each animation "step", which lets you do the synchronization yourself (while still harnessing all the built-in power of the "animate" function).
var initialLeft = $("#TheElement").css("left");
$("#TheElement").animate({
width: "917px",
height: "228px"
}, {
step: function(now, fx) {
if (fx.prop == "width") {
$("#TheElement").css("left", initialLeft - now);
}
}
);
Now the width and left offset are kept perfectly in sync. (As I said, the step function seems undocumented, but you can output the "fx" object in something like Firebug to see all its properties. The key one is "fx.prop", which is the CSS property that the "step" callback is referencing. The first callback parameter, "now", is a shortcut to "fx.now", which is the currently calculated value of the CSS property for the current animation step.)
« Back to Blog Main Page
|