Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does JQuery do animations?

JQuery is written in Javascript. As someone who knows a little of each, I have to wonder how they wrote some of it. How do you animate HTML elements in pure Javascript? Is it just repeatedly updating the CSS property that is to be animated, using standard DOM manipulation, with callbacks to make it asynchronous? Or is it something more sophisticated?

like image 911
McGarnagle Avatar asked Mar 28 '12 22:03

McGarnagle


1 Answers

jQuery animations are just updating CSS properties on a recurring timer (which makes it asynchronous).

They also implement a tweening algorithm which keeps track of whether the animation is ahead of schedule or behind schedule and they adjust the step size in the animation at each step to catch up or slow down as needed. This allows the animation to finish in the time specified regardless of how fast the host computer is. The downside is that slow or busy computers will show more choppy animations.

They also support easing functions which control the time/shape of the acceleration of the animation. Linear means a constant speed. Swing is a more typical, start slow, accelerate to max speed in the middle and then end slowly.

Because animations are asynchronous, jQuery also implements an animation queue so that you can specify multiple animations that you want to see execute one after the other. The 2nd animation starts when the first animation finishes and so on. jQuery also offers a completion function so if you want some of your own code to run when an animation is complete, you can specify a callback function that will get called when the animation completes. This allows you to carry out some operation when the animation is complete such as start the animation of some other object, hide an object, etc...

FYI, the jQuery javascript source code is fully available if you want more details. The core of the work is in a local function called doAnimation(), though much of the work is done in functions called step and update which can be found with the definition of jQuery.fx.prototype.

like image 78
jfriend00 Avatar answered Sep 23 '22 03:09

jfriend00