I had someone write in about this as related to my course Learning jQuery From Scratch. It might seem obvious after you've learned it, but I can remember being confused about it so I can relate.

jQuery makes "chaining" very easy. Take one collection of elements and do, do, do, do.

  // this is CHAINING
$(".thing")
  .addClass("cool")       // do this!
  .animate({              // then do this!
    "padding": 20
  }, 4000)
  .css("color", "red");   // then do this!

With chaining, those three things will all happen in that order and immediately. The weird part is the waiting. What waits for what?

Those three calls are syncronous. So by the time animate is called, the element will have the class name "cool" applied, because it does wait for the syncronous call above it. But when that animation starts, the color of that element will be red. The call to animation is still syncronous, so it happened first, but the next call doesn't wait for the animation to actually finish. That part is asyncronous.

So what if you do want the next call to wait for the animation to finish before doing the next thing? That's what callbacks are for.

That looks like this:

  // this is a CALLBACK
$(".thing")
  .animate({              // do this
    "padding": 20
  }, 4000, function() {
    $(this).css("color", "red"); // do this when animation finishes
  });

It's all about timing.


4,174 4 21