X10nD
X10nD

Reputation: 22050

fadeout() images with delay using jQuery

I have about 10 images, which I want to fade out, but delay the fadeout show that each image is shown clearly.

    for(i=1;i<=24;i++) {
 $('.stretch').fadeOut(5000).attr('src','images/hello'+i+'.jpg');
     }

I want to use jQuery.

Thanks Jean

Upvotes: 1

Views: 817

Answers (3)

Peter Ajtai
Peter Ajtai

Reputation: 57715

Caution: attr('src', 'blah') will SET the src TO blah... I don't think that's what you want here are some alternatives:

Why don't you have all those images share a class name, then you remove the need for the for loop, and you can simply fade all the images using the class name?

$('.chosenImage', '.stretch').fadeOut(5000);

The above is equivalent to using the CSS

$('.stretch .chosenImage').fadeOut(5000);

Just be careful that you put the parent first in the CSS version, and the child first in the comma separated JQuery syntax version.

The above will go to work on all of the chosenImage class items that are children of a stretch class item.


You can use regex: This will get all helloXX where XX is a one or two digit number... you can refine the regex to only pick up 1 - 24 if you want.

$('img', '.stretch').filter(function(){
    return $(this).attr('src').match(/images\/hello[0-9]{1,2}.jpg/);
}).fadeOut(5000);

This code takes all the IMGs within the .stretch class and it filters them using a regular expression on each IMGs src attribute.


To have them fade one after another, you would just target each image one by one and put an increasing delay on them... something like this:

var delayIt = -1000;
$('img', '.stretch').each(function(){                
    delayIt += 1000;
    $(this).delay(delayIt).fadeOut(5000);
});

This will fade each image in the class stretch one after another.


Some pertinent JQuery references:

attr()

delay()

each()

fadeOut()

Upvotes: 4

jasonpgignac
jasonpgignac

Reputation: 2306

This is off the top of my head, but the basics of it are this: you'll need to do an each function, with a slightly longer pause each time. The timing of course would differ considerably, but something like this should give you an idea:

delayTime = 0;
jQuery('.stretch').each( function() {
  jQuery(this).delay(delayTime).fadeOut(5000);
  delayTime = delayTime + 5000;
});

So, again, that's an untested snippet, but the concept is simple - you're basically saying I want to fade the first one right away, then fade the second one 5000 later, then the third one 5000 after that, etc, etc.

Does that make sense?

Upvotes: 1

antyrat
antyrat

Reputation: 27765

Try this code:

for(i=1;i<=24;i++) {
        $('.stretch').fadeOut(function() { 
            $(this).load(function() { $(this).fadeIn(); }); 
            $(this).attr('src','images/hello'+i+'.jpg');
        });
}

Upvotes: 0

Related Questions