views:

126

answers:

1

Why doesn't this work right? The effect I am trying to achieve is the blocks move from left to right, and start "pushing" the next ones along. It seems to be a problem with nested callbacks performing animations on the outer elements.

Can anyone explain this? It sorta works, but everything moves too many times.

<html>
<head>
<style>
.item { width: 49px; height: 49px; border: 1px solid orange; background-color: #ccccff; }
#i0 { position: absolute; left: 0px; }
#i1 { position: absolute; left: 150px; }
#i2 { position: absolute; left: 200px; }
#i3 { position: absolute; left: 250px; }
#i4 { position: absolute; left: 400px; }
#i5 { position: absolute; left: 450px; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
<script>
jQuery(function() {
  $("#i0").animate({left:"+=100"}, function() { 
    $("#i0,#i1,#i2,#i3").animate({left:"+=100"}, function() { 
      $("#i0,#i1,#i2,#i3,#i4,#i5").animate({left:"+=50"});
    });
  });
});
</script>
</head>
<body>  
  <div id="i0" class="item"></div>
  <div id="i1" class="item"></div>
  <div id="i2" class="item"></div>
  <div id="i3" class="item"></div>
  <div id="i4" class="item"></div>
  <div id="i5" class="item"></div>
</body>
</html>
+3  A: 

The second argument to animate() is a callback that gets called when the animation completes. Since $("#i0,#i1,#i2,#i3").animate(..) animates 4 things, it calls its callback 4 times. An approach like this might work:

function move(i, left, callback) {
  $("#i"+i).animate({left:left}, callback);
}

function sequence(n, left, callback) {
  return function() {
    var i = 0;
    for (; i < n; i++) {
      move(i, left);
    }
    move(i, left, callback);
  }
}

jQuery(function() { move(0, "+=100", sequence(3, "+=100", sequence(5, "+=100"))) });
dbarker
Could you offer a solution? I'd like a callback once after all elements are done animating. How could I do this?
Mark Renouf