bbtimx bbtimx - 3 months ago 17
jQuery Question

jQuery animate wont go to target number

I whant to animate a percentge to 100 but jQuery animate sometimes stop at 99!

JS code:

count = 15;
total = 15;

var now = Math.ceil(( count / total ) * 100);
$('.Count').html('<strong>' +now + '</strong> ');
$({countNum: 0}).animate({countNum: now}, {
duration: 1000,
easing: 'linear',
step: function () {
$('.Percent').html('<strong>' + Math.ceil(this.countNum) + '</strong> %');
}
});


HTML:

COUNT: <span class="Count"></span><br />
PERCENTAGE: <span class="Percent"></span>


Jsfiddle: http://jsfiddle.net/MbRE9/464/

You must give it some tries to see it will not always end up at 100 %.

Answer Source

step only runs while your animation is active, it does not guarantee the last step will happen at 100%. You need to run your custom function inside done property of animate() to make sure that code is run when the animation has completed:

/*...*/.animate({/*...*/},{
  /*...*/,
  step: function(){
    $('.Percent').html('<strong>' + Math.ceil(this.countNum) + '</strong> %');
  },
  done: function(){
    $('.Percent').html('<strong>' + Math.ceil(this.countNum) + '</strong> %');
  }
}

If you don't want to write it twice, place it in a variable:

count = 15;
total = 15;

var now = Math.ceil(( count / total ) * 100),
    cNumUp = function(num) {
      $('.Percent').html('<strong>' + Math.ceil(num) + '</strong> %');
    };
$('.Count').html('<strong>' +now + '</strong> ');

$({countNum: 0}).animate({countNum: now}, {
  duration: 1000,
  easing: 'linear',
  step: function(){cNumUp(this.countNum)},
  done: function(){cNumUp(this.countNum)}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
COUNT: <span class="Count"></span><br />
PERCENTAGE: <span class="Percent"></span>