Edentity Web Systems
You solve creative. We crack code.
/Header/WhoWeAre.jpg
 

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 |

4 Comment(s)

There's good info here. I did a search on the topic and found most people will agree with your blog. Keep up the good work mate!
I don't know If I said it already but ...Hey good stuff...keep up the good work! :) I read a lot of blogs on a daily basis and for the most part, people lack substance but, I just wanted to make a quick comment to say I'm glad I found your blog. Thanks,) A definite great read....
Hey, great blog...but I don’t understand how to add your site in my rss reader. Can you Help me, please :)
thanks a lot for that great advice... by this i built a horizontal accordion menu with just jquery and a few lines of code... fantastic

Leave Comment

Name:
Comment:  
 
Security Check: 
 
 
Edentity Web Systems Inc.
Suite 201
40 Spadina Ave.
Toronto ON
M5V 2H8
Tel:
416.591.2500
Fax:
416.352.5270
Home | Who We Are | What We Do | Clients & Brands | Careers | Contact

Copyright © 2010 Edentity Web Systems Inc. Privacy Policy