SaintCad
SaintCad

Reputation: 59

fadeOut not working properly after a few cycles

I can't help thinking there is an obvious answer but I cannot find it. In the HTML I have one image on top of another one. The idea is the topimage fades out revealing the bottomimage. I change the id of the bottomimage to topimage (so it will fade out on the next cycle) and add a new bottomimage. The function cycles every 3000ms. Everything works exactly as I want but the 3rd image and everyone there after will not fade.

Why not?

function rotator() {
  $("#topimage").fadeOut(1500);     //fadeout top picture over 1.5 seconds

  newtop = document.getElementById("bottomimage");
  newtop.setAttribute("id", "topimage");
  newtop.zIndex = "2";
  count = (count+1) % 5;

  //add new bottomimage
  next = document.createElement("img"); //create a new image
  next.setAttribute("id", "bottomimage");
  next.src = picts[count];
  next.style.position = "absolute";
  next.style.zIndex = "1";
  document.getElementById("slideshow").appendChild(next);
}   //end rotator

Upvotes: 0

Views: 68

Answers (1)

bitifet
bitifet

Reputation: 3659

jQuer.fadeout() does'nt remove the element from DOM: just hide it. So you end up having more than one elements with the same id, which is illegal.

I suggest you to use a class instead.

On the other hand, why are you mixing jQuery and not jQuery code? If you start using jQuery, better implement the whole function using it.

…this way you also does'nt need to use even a class: simply start with:

var top = $("#topimage").fadeout(1500);

…and finally replace it with new one:

var newimg=$(…)
…
top = newimg;

…and loop again.

HEY!

Now I just noticed you are not chaining effects. This is the actual reason that makes it to not work:

jQuery.fadeOut() exits IMMEDIATELY to avoid blocking JavaScript loop. So you are creating and fading all images in paral.lel. This way you should end up seeing only the first and then the last image if I'm not wrong (and your browser is'nt too slow).

You should chain fadings using a callback (see jQuery.fadeOut() documentation) or, better, use timeout event to avoid infinite call stack (and exponential memory consumtion due to recursive closure scope exposition).

Upvotes: 1

Related Questions