Rimil Dey Rimil Dey - 1 month ago 11
CSS Question

jQuery .each() method doesn't iterate over all images

I am trying to make an image carousel. I am using the jQuery .each() method to iterate over all the images in the div with class="slideshow".

HTML code

<div class="slideshow">
<img src="images/page-1-hero-image.jpg" alt="school's image" class="img-responsive page-one-pic mySlides">
<img src="images/Capture2.PNG" alt="school pic" class="img-responsive mySlides">
<img src="images/Capture.PNG" alt="school pic" class="img-responsive mySlides">
<img src="images/Capture3.PNG" alt="school pic" class="img-responsive mySlides">
</div>


CSS code

.mySlides {
display: none;
position: fixed;
left: 0;
top: 0;
z-index: 1;
/* to make pic responsive */
min-height: 100%;
min-width: 1024px;
width: 100%;
height: auto;
}


Javascript:

function carousel() {
$(".slideshow > img").each(function(index, element) {
$(element).fadeIn(1000).delay(2000);
setTimeout(carousel, 1000);
});
}


The function only fades in the first image and then stops. The other images are not displayed.

here is the link to the hosted project:
https://rimildeyjsr.github.io/St.Anthony-Website/

Avi Avi
Answer

Just an improvement to the previous answer, you can do it in the form of a callback(which ensures you that the function is called only after the fadeIn has occurred or happened, so you wont need a setTimeout) as follows

function carousel() {
    var imgs = $(".slideshow > img");
    imgs.each(function(index, element) {   
        $(element).delay(index * 2000).fadeIn(1000, function() {
            if (index + 1 >= imgs.length) {
                carousel(); // call the function only after all images are fadeIn completed
            }
        });
    });
}

See if that helps and if not drop a comment below

Edit:

After .fadeIn() does it's job, it sets the display value to block what you have to do here is, hide the elements before continuing the slideshow animation, for simplicity we'll set all the img elements display to hidden by using .hide(0). This sets the elements display to none

function carousel() {
    var imgs = $(".slideshow > img");
    imgs.stop().hide(0); // hide all the images whenever the carousel() is called
    imgs.each(function(index, element) {   
        $(element).delay(index * 2000).fadeIn(1000, function() {
            if (index + 1 >= imgs.length) {
                carousel(); // call the function only after all images are fadeIn completed
            }
        });
    });
}

Let me know if you need anything else