[javascript] jQuery animated number counter from zero to value

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

Working

jQuery

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


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));
    }
  });
});

This question is related to javascript jquery html animation each

The answer is


This worked for me

HTML CODE

<span class="number-count">841</span>

jQuery Code

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

You can do it with animate function in jQuery.

$({ countNum: $('.code').html() }).animate({ countNum: 4000 }, {
    duration: 8000,
    easing: 'linear',
    step: function () {
        $('.yourelement').html(Math.floor(this.countNum));
    },
    complete: function () {
        $('.code').html(this.countNum);
        //alert('finished');
   }
});

Demo


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>

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));
        }
    });
});

This is work for me !

<script type="text/javascript">
$(document).ready(function(){
        countnumber(0,40,"stat1",50);
        function countnumber(start,end,idtarget,duration){
            cc=setInterval(function(){
                if(start==end)
                {
                    $("#"+idtarget).html(start);
                    clearInterval(cc);
                }
                else
                {
                   $("#"+idtarget).html(start);
                   start++;
                }
            },duration);
        }
    });
</script>
<span id="span1"></span>

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


This is working for me

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

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/

You can get the element itself in .each(), try this instead of using this

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to animation

Simple CSS Animation Loop – Fading In & Out "Loading" Text Slidedown and slideup layout with animation How to have css3 animation to loop forever jQuery animated number counter from zero to value CSS Auto hide elements after 5 seconds Fragment transaction animation: slide in and slide out Android Animation Alpha Show and hide a View with a slide up/down animation Controlling fps with requestAnimationFrame? powerpoint loop a series of animation

Examples related to each

jQuery animated number counter from zero to value How to iterate over array of objects in Handlebars? Excel VBA For Each Worksheet Loop jQuery looping .each() JSON key/value not working jQuery '.each' and attaching '.click' event How to use continue in jQuery each() loop? jQuery .each() with input elements C++ for each, pulling from vector elements jQuery each loop in table row Get href attribute on jQuery