jqueryanimationjquery-selectorsinfinite

Jquery animation infinite loop with next


I want to animate the pictures of my html page one by one and loop it infinetely. I'm using the code below with the next method, but I can't find an easy way to restart the function. If I try to launch the same function from inside the function that doesn't do the trick as I want the pictures to animate one after the other. How can I restart my loop with next from the first item?

Thanks in advance, here is the code

function animationfade() {

     $('img').first().fadeIn(500).fadeOut(2000, function nextone() {
        $(this).next('img').fadeIn(500).fadeOut(2000,nextone);
      });
    animationfade();
};

animationfade();

Solution

  • You first need to wait until the fadeOut is done, than call fadeIn. Depending on your CSS it might be better to use opacity option:

    (function () {
        var index = 0;
        var $imgs = $('img');
    
        var animationfade = function () {
            $imgs.eq(index).animate({opacity: 0}, 500, function () {
                index = (index + 1) % $imgs.length;
    
                $(this).animate({opacity: 1}, 2000, animationfade);
            });
        };
    
        animationfade();
    })();