Done!

Increment Number using animate function with comma in JQuery


Suppose you want to increment number from 400 to 400000 for a duration of 5 second, ensuring the number is separated by comma. Following code demonstrate how to achieve this.

HTML

<div id="currency"> <div>

JQuery


// Animate the element's value from 400 to 400000:
var currency = $("#currency"); //[make sure this is a unique variable name]

$({someValue: 400}).animate({someValue: 400000}, {
    duration: 5000,
    easing:'swing', // can be anything
    step: function() { // called on every step
      // Update the element's text with rounded-up value:
      currency.text(commaSeparateNumber(Math.round(this.someValue)));
    },
    done: function() {
        alert('animation complete');
    }
});

/**
 * Format the number, so it will be seperated by comma
 */
function commaSeparateNumber(val){
    while (/(\d+)(\d{3})/.test(val.toString())){
      val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
    }
    return val;
}