jQuery animated number counter from zero to value - counter shows wrong value when a value is hundreds of thousands

I have tried to animate the numbers with the help of this URL: jQuery animated number counter from zero to value and followed this code:

$('.count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 3000,
        easing: 'swing',
        step: function (now) {
          $(this).text(Math.ceil(now));
        }
    });
});

The issue is, I gave a number 800 000 to increment in the numeric counter. Randomly this value is incremented and decremented again to 0. For e.g. After incrementing the value up to 800 000, it is again animating back to value 0.

Counter for zero to value is working fine for smaller values in thousands.

1 answer

  • answered 2019-10-15 13:39 Miroslav Glamuzina

    Something like this should do the trick,

    $('.count').each(function() {
      $(this).prop('Counter', 8000)
        .animate({
          Counter: $(this).text()
        }, {
          duration: 3000,
          easing: 'swing',
          step: function(now, a) {
            $(this).text(8000 - ~~this.Counter);
          }
        });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <span class='count'>0</span>

    Hope this helps,