Thursday, March 10, 2016

jQuery animate fired the callback twice

Animate would fire the callback twice because it calls its callback once for each element in the set you call animate on.

Because the animation works on body on some browsers but on html on other browsers. We can solve this issue by using .promise().then:

    $('html, body').animate({
      scrollTop: $('#test').offset().top,
    }, 400, function(){
      console.log('this will be fired twice');
    })
    .promise().then(function() {
      // Called when the animation in total is complete
      console.log('this will be fired once');
    });

No comments: