views:

3904

answers:

2

This question is similar to this one about animation queues, but the answers in that thread are very specific and not easily generalised.

In my web application, messages are reported back to the user (info boxes, errors & warnings, etc) by outputting a div with class="alert" eg:

<div class="alert">Login successful</div>
<div class="alert">You have new messages waiting</div>

There could be any number of alerts on a page, depending on what the user does.

What I'd like is to use a jQuery animation to show each of the alert boxes sequentially: once one animation ends, the next one begins.

The answers in that other question said to use a callback like:

$('#Div1').slideDown('fast', function(){
    $('#Div2').slideDown('fast');
});

except that won't work if there's an unknown number of divs to animate. Anyone know of a way to achieve this?

+1  A: 

I came up with a solution, though I get a sneaking suspicion that someone who knows more about JS closures might have a few pointers for me.

nextAnim($('.alert'));

function nextAnim($alerts) {
    $alerts
        .eq(0)    // get the first element
        .show("slow",
            function() {
                nextAnim($alerts.slice(1));  // slice off the first element
            }
        )
    ;
}
nickf
A few "pointers"? Good one.
harpo
+2  A: 

It's easy enough to set up:

// Hide all alert DIVs, then show them one at a time
$(function()
{
   var alerts = $(".alert").hide();
   var currentAlert = 0;
   function nextAlert()
   {
      alerts.eq(currentAlert).slideDown('fast', nextAlert);
      ++currentAlert;
   }
   nextAlert();
});

You could probably make a simple plugin method out of this if it's something you'll be using a lot.

Shog9