O.M.N.L
O.M.N.L

Reputation: 207

jQuery animation delays callback execution

I try to animate 3 images from left to right, starting stacked on top of each other. The third animation should start immediately but it's delayed. What's the reason?

$('.image').animate({left: '100px'}, 500, function () {
    $('.image:eq(1), .image:eq(2)').animate({left: '250px'}, 500, function () {
        $('.image:eq(2)').animate({left: '400px'}, 500);
    });
});

Edit: I'd like to reveal only 1 image per animation.

https://jsfiddle.net/azeL7mwk/1/

Upvotes: 0

Views: 37

Answers (1)

DDomen
DDomen

Reputation: 1878

$('.image').animate threat and animate each single element, so you are actually calling the first callback function 3 times, the second 2 * 3 times and if you put a callback on the third animate you would call it 1 * 6 times. This is not the beahviour you are looking for.

You can see this effect by doing a simple console log:

$('.image').animate({left: '100px'}, 500, function () {
  console.log(1)
  $('.image:eq(1), .image:eq(2)').animate({left: '250px'}, 0, function () {
    console.log(2)
    $('.image:eq(2)').animate({left: '400px'}, 500, function() {
      console.log(3)
    });
  });
});

// OUTPUT:
// 1
// 1
// 1
// 2
// 2
// 2
// 2
// 2
// 2
// 3
// 3
// 3
// 3
// 3
// 3

I suggest to animate the first image, then move instantly the second image behind the first and animate it, and the same for third and second images.

$('.image:eq(0)').animate({left: '100px'}, 500, function () {  
    $('.image:eq(1)').css({left: '100px'}).animate({left: '250px'}, 500, function() {
      $('.image:eq(2)').css({left: '250px'}).animate({left: '400px'}, 500);
  });
});

You can also achieve this by separating the animations queues, much way better and cleaner:

$('.image:eq(0)')
  .animate({left: '100px'}, 500);

$('.image:eq(1)')
  .animate({left: '100px'}, 500)
  .animate({left: '250px'}, 500);

$('.image:eq(2)')
  .animate({left: '100px'}, 500)
  .animate({left: '250px'}, 500)
  .animate({left: '400px'}, 500);

You could also delay the animations, but the easing would mess up things a little bit

Upvotes: 1

Related Questions