Search code examples
jqueryanimationloopschaining

How to animate through a list of elements using jQuery?


I have a list items of cars that I'd like to animate through.

<li id="toyota">
    <img class="car" src="img/toyota.png">
</li>
<li id="honda">
    <img class="car" src="img/honda.png">
</li>
<li id="ford">
    <img class="car" src="img/ford.png">
</li>

I'm assuming I'd have to store them in an array and then loop through them?

I'm pretty new to jQuery/JS, but I sort of understand the concepts. I want to animate through each car so that one appears after another. Something like this:

$('.car').fadeIn(1000, function(){
    $('.car').fadeOut(1000);
});

Thanks!


Solution

  • Try the following:

    var cars = $('.car');
    var index = 0;
    var loop = function() {
      var car = $(cars[index]);
      car.fadeIn(1000, function() {
        car.fadeOut(1000, function() {
          index = index + 1 < cars.length ? index + 1 : 0;
          loop();
        });
      });
    };
    loop();
    

    This will fadeIn a car, then fade it out, once it has faded out it will fadeIn the next car, continuing round to the first car again.