Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

$({ 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));     }   }); }); 
like image 953
DreamTeK Avatar asked Apr 11 '14 07:04

DreamTeK


2 Answers

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)); } 
like image 173
floribon Avatar answered Oct 07 '22 20:10

floribon


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

like image 25
adeneo Avatar answered Oct 07 '22 22:10

adeneo