I’m trying to iterate over two or more layers, fading one out and the next in.
At the start, both layers have the style “display:none;” – therefore, at the first method call, I just fadeIn() element .eq(0) – after that, I always fadeOut() .layer:visible and fadeIn() .eq(currentSlide).
currentSlide was initialized with 0 before and gets iterated at each call.
A no-brainer, one would think.
But here is what happens:
Whenever the animation starts, the first element gets faded in twice – after that the animation runs as expected, but the elements are in different order. The first element in the markup suddenly is .eq(1) and the second one is at index .eq(0).
If I remove display:none; from the layers, everything works perfect – it must be related to the visibility settings and maybe a selector not seeing the layers?
(But .children().length() always gives me the correct number though…)
The markup:
<div class="elements">
<div class="layer"><img src="uploads/pics/one.png" /></div>
<div class="layer"><img src="uploads/pics/two.png" /></div>
</div>
The jQuery plugin method written in coffescript:
if element.find('.layer:visible').length > 0 and element.find('.elements').children().length > 1
element.find('.layer:visible').fadeOut -> element.find('.elements').children().eq(currentSlide).fadeIn()
else
element.find('.elements').children().eq(0).fadeIn()
# Iterate over slides or reset to zero if last one is reached
if currentSlide < element.find('.elements').children().length - 1
currentSlide++
else
currentSlide = 0
When you write
there’s a delay (by default, 400ms) before the callback is invoked. During that time, the
currentSlideincrement code is called; soeq(currentSlide)is called with that value, rather than the value ofcurrentSlidewhenfadeOutwas called.Does this explain the behavior you’re experiencing? Try substituting