Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery animation queues across multiple elements

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?

like image 539
nickf Avatar asked Feb 02 '09 23:02

nickf


2 Answers

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
            }
        )
    ;
}
like image 194
nickf Avatar answered Oct 06 '22 00:10

nickf


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.

like image 30
Shog9 Avatar answered Oct 06 '22 00:10

Shog9