John Wu
John Wu

Reputation: 1025

jQuery animation doesn't run fluently

I am learning how to schedule animations via JavaScript, especially with the help of jQuery. I tried to blink some h1 tags, but the animation doesn't seem to run fluently. It stops for a while and then go on.
The core animation code:

function animSlideHeading() {
  $('.slide h1').animate({
    opacity: .6
  }, 500, 'swing', function() {
    $('.slide h1').animate({
      opacity: 1
    }, 500, 'swing', animSlideHeading);
  });
}

See this JSBin.

Upvotes: 2

Views: 314

Answers (1)

adeneo
adeneo

Reputation: 318322

There are several elements matching the selector $('.slide h1'), so the callback is called multiple times, once for each element that is animated, and animSlideHeading runs more and more times the longer it goes, messing it up.

To solve it, you can use promises that resolve when the animations have completed for all the elements in the collection collectively

function animSlideHeading() {
    $('.slide h1').animate({
        opacity: 0.6
    }, 500, 'swing').promise().done(function () {
        $(this).animate({
            opacity: 1
        }, 500, 'swing').promise().done(animSlideHeading);
    });
}
animSlideHeading();

FIDDLE

Upvotes: 2

Related Questions