How to animate a set of jQuery objects one at a time (instead of all at once)

I am trying to create an image slider. (I know there are many plugins out there, but this is more for educational purposes).

Basically, I have a set of images with z-index: 0. What I'm trying to do is take a set of images, then select each of the images and change the index to 1, animate the opacity and then return it to 0, so the following the image will do the same.

This is the first part, but the problem is that when I test this part, all the images make animation at the same time. Instead of doing one after another. I know that you can use callback functions such as:

image1.animate(the animation, function({ image2.animation(the animation, function({ image3.animation(the animation, function}) etc... 

})

But if I had more images, it would get complicated. I am trying to find a more efficient way to do this, but I cannot find an answer.

Here is what I tried:

 images.each(function () { $(this).css({ "opacity" : "0.0", "z-index" : "1" }).animate({ opacity: "1.0" }, 3000); }); 

but that will not work. All images make animation at the same time. I even tried with a for loop, but I get the same thing:

 for (var i=0; i<images.length; i++){ images.eq(i).css({ "opacity" : "0.0", "z-index" : "1" }).animate({ opacity: "1.0" }, 3000); } 

I know that I am doing something wrong, but I cannot understand what it is. If someone helps, it will be very helpful!

+8
jquery
source share
3 answers

Use .delay() , for example:

 images.each(function (i) { $(this).delay(3000*i) .css({ opacity : 0, "z-index": 1 }) .animate({ opacity: 1 }, 3000); }); 

Since this uses the index of the element passed as the first parameter to the .each() , the first is delayed by 3000*0 ms, so it’s not at all, the second is delayed by 3000 ms, etc., so they come to life one after another.

+11
source share

If you don't want to use delay (as I did), you can do something like this using a recursive function.

 function animateImage(images, i) { $(this).css({ "opacity" : '0.0', "z-index" : "1" }).animate({ opacity: "1.0" }, 3000, function() { var next = i + 1; if (next < images.length) { animateImage(images, next); } }); } animateImage(images, 0); 
+2
source share

Use .queue() to install them http://api.jquery.com/queue/

-one
source share

Source: https://habr.com/ru/post/650596/


All Articles