mm2887
mm2887

Reputation: 538

How to create a looped animation with JQuery

I have been sitting on this for a few hours and cannot figure this out. I am trying to create an slideshow (3 slides) that loops endlessly. Each slide is a li inside #slideshow. I have walked through this with a debugger and all variables get set correctly, but I don't understand why the animations dont actually happen. I have this which ends up displaying all images on the page:

$(document).ready(function() {
$slideshow = $('#slideshow');

$slideshowItems = $slideshow.find('li');

$slideshowItems.hide();

nextI = function(x) {       
        if ((x+1) < $slideshowItems.length) {
            return x+1;
        }
        else {
            return 0;
        }
    }

animation = function(i) {       
    $slideshowItems.eq(i).fadeIn(500).delay(1000).fadeOut(500, animation(nextI(i)));
}

animation(0);

If I do:

$slideshowItems.eq(0).fadeIn(500).delay(1000).fadeOut(500, 
     $slideshowItems.eq(1).fadeIn(500).delay(1000).fadeOut(500,
         $slideshowItems.eq(2).fadeIn(500).delay(1000).fadeOut(500));

This works as expected, but it seems ugly and does not loop.

Any idea why I can't get this to work? I feel it is something with my expectations of how JQuery/ JS modifies the DOM or the sequence that the browser uses to execute animations. Thank you for the help!

Upvotes: 0

Views: 627

Answers (3)

Jeff Lauder
Jeff Lauder

Reputation: 1247

I would try setting that as a function and then using setInterval:

setInterval(function(){
    $slideshowItems.eq(0).fadeIn(500).delay(1000).fadeOut(500, function() {
       $slideshowItems.eq(1).fadeIn(500).delay(1000).fadeOut(500, function() {
           $slideshowItems.eq(2).fadeIn(500).delay(1000).fadeOut(500);
       });
    });
}, 6000); // 6000 milliseconds before loops

Upvotes: -1

TiC
TiC

Reputation: 21

You should specify a callback method but your "animation(nextI(i))" returns nothing, so nothing remains to do after the fade out is complete.

Something like this I think will work:

var animation = function(i) {       
   $slideshowItems.eq(i).fadeIn(500).delay(1000).fadeOut(500, function (){
      animation(nextI(i));
   });
}

Upvotes: 1

RightSaidFred
RightSaidFred

Reputation: 11327

var $slideshowItems = $('#slideshow').find('li'), 
    i = 0;

(function loop() {

    $slideshowItems.eq( i ).fadeIn(500).delay(1000).fadeOut(500, loop);
    i = ++i % $slideshowItems.length;

})();

JSFIDDLE DEMO

Upvotes: 5

Related Questions