0

I am trying to animate a handful of DIV's to scroll upwards but I want one to scroll up after a pause after the other after the other. And the best I can come up with at the moment is

$('.curtain').each(function()
{
    var $elem = $(this);
    setTimeout(function()
    {
        $elem.animate({"height":0+'px'}, 2000);
    }, 1000);
});

Problem is they still all animate together without pause. How can I go about doing something in this fashion. The divs are dynamically generated and there can be 5 - 20 of them so doing a hardcoded logic is out, any ideas?

2 Answers 2

2
function animateIt () {
    var elems = $('.curtain').get();
    (function next() {        
        if(elems.length){
            var elem = $(elems.shift());
            elem.animate({"height":0+'px'}, 2000, next);
        }
    })();
}
animateIt();

running example

Another way like queue

function animateIt () {
    var divs = $('.curtain');
    divs.each( function(){
        var elem = $(this);
        $.queue(divs[0],"fun", function(next) { elem.animate({"height":0+'px'}, 2000, next); });               
    });
    divs.eq(0).dequeue("fun");
}
Sign up to request clarification or add additional context in comments.

3 Comments

They say that there's more than one way to skin a cat. No where else can you understand this more than on Stack Overflow. That's some slick looking code :P +1 from me!
+1 from me as well and this works nice and smooth.. only thing I need to figure out from this and hopefully I can with a little play is how to make it not necessarily go in sequence like it is, where one starts after the other completes, but starts while the other is running.. ultimately by the time it reaches the last one, they are still all moving up.. think of the row row row your boat song, where other people join in after a verse or two, similar effect if i had to put it verbally.
Well this is not going to work since it will wait til it is done. For that you need to use a setTimeout to start the next like you are doing.
0

Looks like a simple recursive function might work for you here -

function doAnimation(elapsed){
  var iterations = $('.curtain').length;
  var current = elapsed+1;
  if (current <= iterations){
   setTimeout(function(){
      $('.curtain:eq(' + elapsed + ')').animate(...);
      doAnimation(current);
    },50);
  }
}

doAnimation(0);

Here's a simple demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.