Search code examples
javascriptjquerycounter

jQuery Counter, animating to a total, but how do I include a comma?


I have a found a number of solutions on here for a counter, animating from one total to another.

Here's my what I'm using now:

jQuery.fn.extend({
          ts : function (from, to, time) {
            var steps = 1,
                self = this,
                counter;
        
            if (from - to > 0) {
              steps = -1;
            };
        
            from -= steps;
        
            function step() {
              self.text(from += steps);
        
              if ((steps < 0 && to >= from) || (steps > 0 && from >= to)) {
                clearInterval(counter);
              };
            };
        
            counter = setInterval(step, time || 5);
          }
        });
        
        
        var total = $('.total').ts(56000,56941);

It works well. However, I would like to add a comma to the total, something like 56,941. Is this possible?


Solution

  • This will work. The function is taken from http://ntt.cc/2008/04/25/6-very-basic-but-very-useful-javascript-number-format-functions-for-web-developers.html. Very handy

    jQuery.fn.extend({
              ts : function (from, to, time) {
                var steps = 1,
                    self = this,
                    counter;
    
                if (from - to > 0) {
                  steps = -1;
                };
    
                from -= steps;
    
                function step() {
                  self.text(addCommas(from += steps));
    
                  if ((steps < 0 && to >= from) || (steps > 0 && from >= to)) {
                    clearInterval(counter);
                  };
                };
    
                counter = setInterval(step, time || 5);
              }
            });
    
    
    var total = $('.total').ts(56000,56941);
    
    
    function addCommas(nStr)
    {
      nStr += '';
      x = nStr.split('.');
      x1 = x[0];
      x2 = x.length > 1 ? '.' + x[1] : '';
      var rgx = /(\d+)(\d{3})/;
      while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
      }
      return x1 + x2;
    }