views:

14214

answers:

6

I have a bunch of images that need to rotate in and out one at a time every 2 seconds with fancy JQuery fadeIn and fadeOut. I have all the images in the HTML to pre-load them and a setInterval timer that fades the current image out, then fades the next image in. Problem is that sometimes when you are clicking or scrolling during the fade in/out process, the JS gets interrupted and the current image never disappears and the next one fades in giving you two images.

I get the feeling it has something to do with setInterval not running properly every 2 seconds, but are there any better ways to accomplish what I need?

Here's a snippet of code:

HTML

<a href="javascript:;">
  <img id="img1" src="image1.gif" />
  <img id="img2" src="image2.gif" style="display:none;" />
  <img id="img3" src="image3.gif" style="display:none;" />
</a>

JS

var numImages = 3;
var currentImage = 1;
imageInterval = window.setInterval("changeImage();", 2000);

function changeImage()
{
 $("#img" + currentImage).fadeOut("slow", function() {
  if (currentImage >= numImages)
  {
   currentImage = 0;
  }
  $("#img" + (currentImage + 1) ).fadeIn("slow", function() {
   currentImage++;
  });
 });
}
+1  A: 

You have id="img2" twice.

Can you not simpify - calculate the current and next id first. Then do your $().fadeOut() and on the next line $().fadeIn() and avoid all of the function complexity.

RichH
+2  A: 

Just off the top of my head ... why are you doing the currentImage bookkeeping in the callback functions? It seems to me this is easier, and might even have something to do with your problem:

function changeImage()
{
    $("#img" + currentImage).fadeOut("slow");
    currentImage = (currentImage >= numImages) ? 1 : currentImage + 1;
    $("#img" + currentImage).fadeIn("slow");
}
Jim Nelson
+1  A: 

Your problem is that if you click on img2 before it's finished fading in, currentImage is still thinking you're looking after the transition between img1 and img2, but in reality img2 is now live and you're waiting on img3.

I think that Jim's solution should see you OK.

As a freebee, consider adding this too to allow you to add more images without having to edit the script:

numImages = $("a > img").size();
Steve Perks
+4  A: 

Have you thought about using the Cycle Plugin? It sounds like this does exactly what you're trying to do, and it offers a lot of flexibility. I've used this plugin myself with great results. Highly recommended.

nickf
Wow, incredible plugin. Thanks!
TTT
+1  A: 

also

setInterval (function () {
    $("img:eq(0)").fadeOut ("slow").next ("img").fadeIn ("slow");
}, 2000);
tom
A: 

ok but how to fetch data from mysql and then put it into as a live feed

generalsoftwares
You should ask this as a new question, rather than posting it as an answer. Ask your question here: http://stackoverflow.com/questions/ask
Douglas