jQuery animated number counter from zero to value

150,812

Solution 1

Your thisdoesn't refer to the element in the step callback, instead you want to keep a reference to it at the beginning of your function (wrapped in $thisin my example):

$('.Count').each(function () {
  var $this = $(this);
  jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
    duration: 1000,
    easing: 'swing',
    step: function () {
      $this.text(Math.ceil(this.Counter));
    }
  });
});

Update: If you want to display decimal numbers, then instead of rounding the value with Math.ceil you can round up to 2 decimals for instance with value.toFixed(2):

step: function () {
  $this.text(this.Counter.toFixed(2));
}

Solution 2

this inside the step callback isn't the element but the object passed to animate()

$('.Count').each(function (_, self) {
    jQuery({
        Counter: 0
    }).animate({
        Counter: $(self).text()
    }, {
        duration: 1000,
        easing: 'swing',
        step: function () {
            $(self).text(Math.ceil(this.Counter));
        }
    });
});

Another way to do this and keep the references to this would be

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

FIDDLE

Solution 3

IMPORTANT: It seems like a small difference but you should really use a data attribute to hold the original number to count up to. Altering the original number can have un-intended consequences. For instance, I'm having this animation run everytime an element enters the screen. But if the element enters, exits, and then enters the screen a second time before the first animation finishes, it will count up to the wrong number.

HTML:

<p class="count" data-value="200" >200</p>
<p class="count" data-value="70" >70</p>
<p class="count" data-value="32" >32</p>

JQuery:

$('.count').each(function () {
    $(this).prop('Counter', 0).animate({
            Counter: $(this).data('value')
        }, {
        duration: 1000,
        easing: 'swing',
        step: function (now) {                      
            $(this).text(this.Counter.toFixed(2));
        }
    });
});

Solution 4

What the code does, is that the number 8000 is counting up from 0 to 8000. The problem is, that it is placed at the middle of quite long page, and once user scroll down and actually see the number, the animation is already dine. I would like to trigger the counter, once it appears in the viewport.

JS:

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

And HTML:

 <span class="count">8000</span>

Solution 5

Here is my solution and it's also working, when element shows into the viewport


You can see the code in action by clicking jfiddle
var counterTeaserL = $('.go-counterTeaser');
var winHeight = $(window).height();
if (counterTeaserL.length) {
    var firEvent = false,
        objectPosTop = $('.go-counterTeaser').offset().top;

        //when element shows at bottom
        var elementViewInBottom = objectPosTop - winHeight;
    $(window).on('scroll', function() {
        var currentPosition = $(document).scrollTop();
        //when element position starting in viewport
      if (currentPosition > elementViewInBottom && firEvent === false) {
        firEvent = true;
        animationCounter();
      }   
    });
}

//counter function will animate by using external js also add seprator "."
 function animationCounter(){
        $('.numberBlock h2').each(function () {
            var comma_separator_number_step =           $.animateNumber.numberStepFactories.separator('.');
            var counterValv = $(this).text();
            $(this).animateNumber(
                {
                  number: counterValv,
                  numberStep: comma_separator_number_step
                }
            );
        });
    }


https://jsfiddle.net/uosahmed/frLoxm34/9/
Share:
150,812
DreamTeK
Author by

DreamTeK

Updated on October 23, 2021

Comments

  • DreamTeK
    DreamTeK over 2 years

    I have created a script to animate a number from zero to it's value.

    Working

    jQuery

    $({ Counter: 0 }).animate({
      Counter: $('.Single').text()
    }, {
      duration: 1000,
      easing: 'swing',
      step: function() {
        $('.Single').text(Math.ceil(this.Counter));
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <span class="Single">150</span>


    Not Working

    I now want to run the script several times on the page for each matching class.

    Below is what I am trying but with no success so far:

    HTML

    <span class="Count">200</span>
    <span class="Count">55</span>
    

    JQUERY

    $('.Count').each(function () {
      jQuery({ Counter: 0 }).animate({ Counter: $(this).text() }, {
        duration: 1000,
        easing: 'swing',
        step: function () {
          $(this).text(Math.ceil(this.Counter));
        }
      });
    });
    
  • DreamTeK
    DreamTeK about 10 years
    I couldn't get this to work but thanks for your input.
  • Vilas Kumkar
    Vilas Kumkar almost 10 years
    what if we've decimal numbers?
  • ashicus
    ashicus about 8 years
    @VilasKumkar I know this is an old thread, but for future Googlers, here's how I tweaked the answer to handle decimals, as well as prefix and postfix (for example, "$12.34 Million" (I'm sure it could be cleaner): gist.github.com/ashicus/b18f2831d7d21fc10fe2e47c41922328
  • floribon
    floribon about 8 years
    I've also updated my answer with a way to print numbers with any number of decimals
  • Anahit Ghazaryan
    Anahit Ghazaryan over 7 years
    Thanks for the good snippet @floribon. What i could do for not writing the code twice if i wanna do count down after doing count up with the same code? Any idea?
  • M1lls
    M1lls almost 7 years
    I cannot get the fiddle fiddle that @Obsidian posted to work with a decimal, 100.50 shows up as 101, tried using @ashicus and @floribon code but doesn't work, any ideas? Thanks in advance!
  • LiN
    LiN about 5 years
    how to swing it continuously.
  • MelanieP
    MelanieP over 4 years
    Thank you so much! This is the exact issue I was having with the above.
  • Kurt Lagerbier
    Kurt Lagerbier almost 3 years
    I like this answer, because it has complete method inside. When dealing with big numbers, one can set the final number to be sure it is the value it should be. Thanks!
  • Admin
    Admin over 2 years
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.