Steven
Steven

Reputation: 13975

Multiple Image Fade In/Out

I have about 20 different images that I want to fade in and out in 4 boxes. I need it to randomally select an image from the list of images and display it.

Box example photo1, photo2, photo3, photo4 are their names. They need to be individually named as they absolute positioned.

<div id="photo1">
    <img src="images/photo.jpg" width="300" height="300" />
    <img src="images/photo2.jpg" width="300" height="300" />
    <img src="images/photo3.jpg" width="300" height="300" />
    <img src="images/photo4.jpg" width="300" height="300" />
    <img src="images/photo5.jpg" width="300" height="300" />
</div>

jquery so far

<script type="text/javascript">

//generate random number
var randomnumber=Math.floor(Math.random()*$("#photo1").children().length);
$(function() {
    //hide all the images (if not already done)
    $("#photo1 > img").hide();

    //set timeout for image to appear (set at 500ms)
    setTimeout(function(){
       //fade in the random index of the image collection
       $("#photo1 > img:eq(" + randomnumber + ")").fadeIn();
    }, 500);       
});
</script>

Upvotes: 3

Views: 4800

Answers (2)

karim79
karim79

Reputation: 342625

I've refactored your code:

$(function() {
    // match all divs with ID starting with 'photo'
    $("div[id^=photo] > img").hide();
    setTimeout(function(){
       $("div[id^=photo]").each(function() {
           var rand = Math.floor(Math.random() * $(this).children().length);
           $(this).find('img:eq(' + rand + ')').fadeIn();
       });
    }, 500);       
});

See http://api.jquery.com/attribute-starts-with-selector/

Upvotes: 1

jacques
jacques

Reputation: 61

jQuery Cycle

Very handy.

Upvotes: 0

Related Questions