Eventually I’m trying to create a timed slide show that fades images in and out. What I can’t figure out is why my $.each function does complete the loop for each index of the array and instead only loops the last image seven times.
Here is my code…
<script>
$(document).ready(function(){
var image1 = "<img width='600' height='400' src='images/image1.jpg' />";
var image2 = "<img width='600' height='400' src='images/image2.jpg' />";
var image3 = "<img width='600' height='400' src='images/image3.jpg' />";
var image4 = "<img width='600' height='400' src='images/image4.jpg' />";
var image5 = "<img width='600' height='400' src='images/image5.jpg' />";
var image6 = "<img width='600' height='400' src='images/image6.jpg' />";
var image7 = "<img width='600' height='400' src='images/image7.jpg' />";
var image8 = "<img width='600' height='400' src='images/image8.jpg' />";
var imageArray = new Array(image1, image2, image3, image4, image5, image6, image7, image8);
$.each(imageArray, function(key, value){
$('#slide').html(value);
$('#slide').hide().fadeIn('slow').fadeOut('slow');
});
});
</script>
Again, what ends up happening is that the last image fades in and out 7 times before disappearing. Thanks in advance guys.
I think your issue is that JavaScript execution doesn’t pause whilst
fadeInandfadeOutare doing their thing.Your
eachcall does this:#slidetoimage1.#slide.#slide.#slidetoimage2(because it doesn’t wait forfadeInto finish), overwritingimage1.#slideagain.And so on.
In order to get the outcome you want, you’ll need a recursive function (i.e. a function that calls itself) instead of your
eachcall. This function will need to pass callback functions tofadeInandfadeOut— these functions will get called whenfadeInandfadeOuthave finished executing.E.g.