Creative Juices Bo. Co.

Satisfy Your Thirst For Something Refreshing!

Use jQuery to Queue Your Animations

Using jQuery's ready() method and callback functions to get your animations to queue smoothly

One of my long time followers and most likely my biggest fan, ran into a little jQuery problem the other day and e-mailed me to see if I could help out. Here's what he had to say:

I am trying to get jQuery to do a fade, a slideDown, and a fade. I need to delay each by a few seconds, or ideally have them trigger after the previous effect completes. I can't seem to figure it out. Your an awesome guy, think you can help out?

The secret to getting me to look at something is to call me "Awesome"!


There may be a few other ways of doing this, but the easiest way I found is to use the jQuery effect's built in callback function. This function will get called once the effect finishes doing its thing. So looking at what he was trying to do, he wanted to trigger a fadeIn(), a slideDown() and finally another fadeIn(). Let's assume that he has some elements called header, sidebar and footer to correspond with these. To do the effect que all you need to do is this:

$("#header").fadeIn("slow",function(){  $("#sidebar").slideDown("slow",function(){    $("#footer").fadeIn("slow");  });});

Reading the code you can see that it first attaches a fadeIn to the #header element. We also attached a callback function that triggers the #sidebar element, which performs a slideDown and has a callback function which handles the #footer element. This element does a fadeIn with no callback function. Pretty simple really. So I sent this back to my biggest fan, thinking that I just saved his day and I would get a big thanks, perhaps some presents and maybe even a parade. But no, he shrugs and says this to me:

I understand that part of it... Its the delay or a pause that I can not figure out. I need to load the background picture... wait 5 seconds. Then have the rest of the animation happen on its own...

Geez Louise, why didn't you say so. Ok, so now apparently he wants to load a background image on the body tag (I'm assuming) and then trigger his fadeIn, slideDown and fadeIn. No problem. jQuery has this cool little method called ready(). To do this we just need to modify the code a bit, like so:

$("body").css({   "background-image": "url(background.jpg)",   "background-position": "top center",   "background-repeat": "repeat"}).ready(function(){   $("#header").fadeIn("slow",function(){      $("#sidebar").slideDown("slow",function(){         $("#footer").fadeIn("slow");      });   });});

So now the body tag will load a background image via CSS. Once this happens it will then trigger the first element effect and continue with all the callback functions as before. There you go biggest fan. I'll be expecting that parade soon!

If you would like to see this in action, click here to view an online demo.

Please note, that these examples assume that you have jQuery loaded.