gibberish gibberish - 5 months ago 21
jQuery Question

How to Animate jQuery collection items individually

Animating a jQuery collection of objects seems to animate them all together, as a group, rather than individually.

I have a few DIVs inside a container div and wish to animate them to slide into view sequentially, like a carousel.

This happens whether I use

$.each()
method:

jsFiddle Demo

or a
for
loop:

jsFiddle Demo

I am guessing that is because: the objects are individually animated but the loop does not wait for one animation to finish before beginning the next. The animations are started sequentially, within a few ms of one another, and overlap in their progression.

How can that be fixed?

I tried adding a delay as recommended here, but the result is not ideal.

jsFiddle Demo

There must be a better way. Just a WAG: perhaps by using the Promises interface?



$('.slide').each(function(){
$(this).animate({
left : 0
},1500);
});

/*
for (var n=0; n < $('.slide').length; n++){
$($('.slide')[n]).animate({
left: 0
},1500);
}
*/

/*
$('.slide').each(function(i){
d =(i)*500;
$(this).delay(d).animate({
left : 0
},1500);
});
*/

#slideshow{position:relative;width:100%;height:200px;overflow:hidden;}
.slide{position:absolute;top:0;left:100%;width:100%;height:100%;}
img{width:100%;height:100%;}
#s1{background-color:pink;}
#s2{background-color:palegreen;}
#s3{background-color:wheat;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="slideshow">
<div id="s1" class="slide">
<h2>Slide One</h2>
<img src="http://placekitten.com/500/150" />
</div>
<div id="s2" class="slide">
<h2>Slide Two</h2>
<img src="http://placekitten.com/502/150" />
</div>
<div id="s3" class="slide">
<h2>Slide Three</h2>
<img src="http://placekitten.com/498/150" />
</div>
</div>




Answer

Please have a look at below approach:

https://jsfiddle.net/br0d1tcn/5/

Here we are calling a animate function for each slide one by one:

var totalLength = $('.slide').length;
if (totalLength > 0) {
  animateSlides(0);
}

function animateSlides(n) {
  $($('.slide')[n]).animate({
    left: 0
  }, 1500, function() {
    if (n < totalLength - 1) {
      n++;
      animateSlides(n);
    }
  });

}
Comments