views:

385

answers:

4

I want to fake a simple animation on page load by sequentially revealing several pngs, each appearing instantly but with unique, precisely timed delay before the next one. Using the latest version of jQuery (1.4.2 at writing), which provides a delay method. My first (braindead) impulse was:

$('#image1').show('fast').delay(800);
$('#image2').show('fast').delay(1200);
$('#image3').show('fast');

Of course all come up simultaneously. jQuery doc examples refer to a single item being chained, not handling multiple items. OK... try again using nested callbacks from show():

$('#image1').show('fast', function() {
    $('#image2').show('fast', function() {      
        $('#image3').show('fast', function() {      
        });
    });
});

Looks ugly (imagine doing 10, also wonder what processor hit would be) but hey, it works sequentially! Without delay though. So... chain delay() after show() using a callback function from it (not even sure if it supports one):

$('#image1').show('fast').delay(800, function() {
    $('#image2').show('fast').delay(1200, function() {      
        $('#image3').show('fast');
    });
});

Hm. Opposite result of what I thought might happen: the callback works, but still no delay. So... should I be using some combination of queue and delay instead of nested callbacks? jQuery doc examples for queue again only use one element for example. Guessing this would involve using a custom queue, but am uncertain how to implement this. Or maybe I'm missing a simple way? (For a simple problem!)

+1  A: 

Wild guess here, but what about

$('#image1').show('fast', function() {
    $('#image2').delay(800).show('fast', function() {      
        $('#image3').delay(1200).show('fast', function() {      
        });
    });
});
Jasper De Bruijn
Your wild guess works fine! And the syntax looks obvious to me now <groan>. (Waiting for other solutions that might avoid nesting before checking off, will look back in later today.) Thank you!
boomturn
A: 
Pointy
Thank you for this. I think below poster gave what I was looking for (am at shallow end of the pool!). This is more than I expected, will review it later.
boomturn
A: 

You could simplify it if they're right there together:

function showNext(img) {
  //show, find next image, repeat, when next doesn't find anything, it'll stop
  img.show('fast', function() { showNext($(this).next('[id^=image]')); });
}
//Call the first image to start the chain
showNext($("#image1"));

If they are further apart, just adjust that .next() selector to how to find the next image, or you could assign a class to them all, etc...however you can traverse to the next one works.

Nick Craver
A: 

Using a queue is pretty straightforward:

var imgs = ['#image1','#image2','#image3',...];

function showNext() {
  var img = imgs.shift();
  if (img) $(img).show('fast', showNext);  
}

showNext(); // start
ndp