Adding a delay between individual animations that run

I have an array with the URLs of images that I add to the page as tags img. I add them to hidden ones and disappear when they load. This works, but I would like to add a little delay between each of them so that it does not fade so much at the same time.

function ajaxCallback(data)
{
    if(data && data.images)
        for(var n in data.images)
        {
            var image = $('<img>')
                .prop(data.images[n])
                .css({opacity: 0})
                .appendTo('#output')
                .load(imageLoaded);
        }
}

function imageLoaded()
{
    $(this)
        .animate({opacity: 1});
}

At the moment, if they load quickly enough, they will all gradually disappear. I would like to delay a little between them. Tried to add a challenge delay, but that didn't seem to do much. I think I may have to do something with the queue or something else, but I can’t figure out how to do it.

What is the best way to do this?

+3
source share
3 answers

( ) , , . animate().

+1

setTimeout imageLoaded() ( ) .

function imageLoaded()
{
   var self = $(this);
   setTimeout(function(){
                            self.animate({opacity: 1});
                        }, 
              Math.random()*2000 //will fire sometime between 0 to 2000 milliseconds
             ); 
}
0

Here is one way:

for (var n in data.images) {
    $('<img>').prop('src', data.images[n]).css({ // don't forget "src"
        opacity: 0
    })
      .appendTo('#output')
      .bind('reveal', imageLoaded); // bind a custom event
}

function imageLoaded() {
    $(this).animate({
        opacity: 1
    }, function(){ // wait until animation is done via callback
        $(this).next().trigger('reveal'); // then trigger the next reveal
    });
}

$('#output').find('img:first').load(function() { // when first image is loaded
    $(this).trigger('reveal'); // trigger its event to start the cascade
});

Example: http://jsfiddle.net/redler/mBfpG/

0
source

All Articles