0

I have two images stacked. With setInterval(), the top one fades away, exposing the second. Then the top image switches to the bottom's src while invisible, and becomes opaque again. The second image changes to the next image and waits for the setInterval() to fade the top image and do it all over again.

It all works great, except the first time around; There's no fade. What am I not seeing?

This happens on all firefox and chrome and I assume all others.

HTML

 <script type="text/javascript"> setInterval('swapImage()', 5000); var galleryCount = 3; </script> ... <img id="image" src="images/gallery/01.jpg" /> <img id="imagenext" src="images/gallery/02.jpg" /> 

Javascript

function swapImage(imageToFadeID) { $("#image").animate ( { "opacity": "0" }, "slow", "linear", changeImage() ); }; var i = 1; function changeImage() //counter +1 { i = i + 1; //add "0" to image number "j" if less than 10. if (i < 10) { var j = "0" + i; } else { j = i; } //change top image to match bottom var topImage = document.getElementById("imagenext").src; document.getElementById("image").src = topImage; //make top image reappear document.getElementById("image").style.opacity = '1'; //change out bottom image to next var btmImage = "images/gallery/" + j + ".jpg"; document.getElementById("imagenext").src = btmImage; //reset counter if at end if (i > galleryCount - 1) { i = 0; } } 

1 Answer 1

1

I looks like you're invoking changeImage instead of passing it as a callback to animate:

Wrong:

function swapImage(imageToFadeID) { $("#image").animate ( { "opacity": "0" }, "slow", "linear", changeImage() // <--- !!! Remove the parentheses from this line! ); }; 

Right:

function swapImage(imageToFadeID) { $("#image").animate ( { "opacity": "0" }, "slow", "linear", changeImage ); }; 
Sign up to request clarification or add additional context in comments.

3 Comments

That was it. Thanks! Why can't you use the paranthesis in the complete function? Does that mess up the syntax? What if I needed to use a variable there?
With parentheses it's a function call - changeImage gets invoked and only its return value gets handed to the animate function. Without parentheses it's just the function itself - you hand that to animate(), the animation gets performed and when it's complete animate() invokes that function you passed.
If you need to pass arguments to changeImage, wrap another function around that: animate(..., "linar", function() { changeImage(param1, param2); });

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.