views:

487

answers:

1

Hay all, i've wrote a simple fading gallery with jQuery. It basically loops though a set of images, fading from one to another. It works perfectly, as predicted, until it gets to the last image, it then doesn't fade from the last to the first, just to displays it.

here's my jQuery

$(document).ready(function(){

Zindex = 99999;
i = 0;

$(".flash img").each(function(){
 $(this).css({
  'position':'absolute',
  'z-index':Zindex,
  'display':'none'
 });
 Zindex--;
});

$(".flash img:first").show();

doFade = function(){  
 if( i == 6 ) { i = 0; };  
 $(".flash img:eq("+parseInt(i+1)+")").fadeIn(100);
 $(".flash img:eq("+parseInt(i)+")").fadeOut(1000);  
 setTimeout("doFade()", 2000);
 i++;
};

doFade();

});

note: there's only ever going to be 7 images.

And my markup

<div class='flash'>
 <img src="img/gallery/picture1.jpg" width="780" height="253" alt="Picture1">
 <img src="img/gallery/picture2.jpg" width="780" height="253" alt="Picture2">
 <img src="img/gallery/picture3.jpg" width="780" height="253" alt="Picture3">
 <img src="img/gallery/picture4.jpg" width="780" height="253" alt="Picture4">
 <img src="img/gallery/picture5.jpg" width="780" height="253" alt="Picture5">
 <img src="img/gallery/picture6.jpg" width="780" height="253" alt="Picture6">
 <img src="img/gallery/picture7.jpg" width="780" height="253" alt="Picture7">
</div>

I think the problem lies in the line

if( i == 6 ) { i = 0; };
+2  A: 

Two things are happening when you reach the end of the 'loop' and execute:

if( i == 6 ) { i = 0; };

First, you're fading in i + 1, which is the second image, not the first, because i is now 0.

Second, you are fading out i, the first image, which isn't even visible. That last image being displayed was image 7, when i + 1 was 6.

So you're never hiding the last image, and never showing the first image. A really quick solution for me was to make the fade out statement the first to execute (i is still 'pointing' to the current image) and setting i = -1 instead of 0 when the 'loop' ends.

doFade = function(){
    $(".flash img:eq("+parseInt(i)+")").fadeOut(1000); 
    if( i == 6 ) { i = -1; }
    $(".flash img:eq("+parseInt(i+1)+")").fadeIn(100);             
    setTimeout("doFade()", 2000);
    i++;
};

However, this does seem to interrupt the flow of the transitions when starting the loop over (I guess because the fade statements are now separated by logic). A simple fix for that should be as easy as introducing current and next variables and doing all logic at the beginning, using those variables in the fade statements.

thorncp