Search code examples
jqueryimageeffectsfade

Applying effects to Images in sequence


I started jQuery this morning (so I'm a noob) and it seemed promising at first but then this...

The idea is to fade in and fade out images one after another with a delay. But they all are faded in at the same time and then faded out. I want them to do that one after another.

Tried modifying the single <img> tag, then filling with html() a <div>, then this and couple other things. This might be a piece of cake but I just don't see it!

<html>
<head>
<style type="text/css">

    span.button{
        display:block;
        width:10px;
        border:1px solid;
        float:left;
        background:#eeeeee;
        padding:5px;
        margin:5px;
        font-weight:bold;
        color:#333333;
        cursor:pointer;
        border-radius:7px;
        border-color:#555555; 
        box-shadow: 0px 0px 2px #777777;
    }

img.gImages{
    border:1px solid;
    border-left-color:#eeeeee;
    border-top-color:#eeeeee;
    border-right-color:#666666;
    border-bottom-color:#666666;
    border-radius:5px;
    height:300px;
    box-shadow: 0px 0px 5px #777777;
}
</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var numOfimgs=3;
$(document).ready(function(){

function preloadImages(numOfimgs){
    var i=0;
    for(i=1; i<numOfimgs+1; i++){
        $("div").append('<img class="gImages" id="'+i+'slika" src="'+i+'.jpg" />');
        $("img#"+i+"slika").hide();
        $("div").append(i);
    }
}
preloadImages(numOfimgs);

function animateImage(imgId){
    $("img#"+imgId+"slika").fadeIn("slow");
    $("img#"+imgId+"slika").fadeOut("slow");
}

function startAnimation(){
var i=0;
for(i=1; i<numOfimgs+1; i++){
    animateImage(i);
    }
}

startAnimation();
});
</script> 
</head>

<body>
<div></div>
<span>below the div</span>
</body>
</html>

Solution

  • How about this:

    function sequencedFade(imgIndex, numImages) {
        if(imgIndex <= numImages) {
            //... your other random stuff here
            $("#"+imgIndex+"slika").fadeOut('slow', function() { sequencedFade(imgIndex++, numImages) });
            //... more other random stuff
        }
    }
    
    sequencedFade(0, 3);
    

    This uses the callback function of fadeOut which is executed upon animation completion.

    http://jsfiddle.net/9KYqJ/