1

I have a jQuery counter which works great. The only problem is, when I have a number in data-target which is formatted (eg. 10,000 instead of 10000), it doesn't work and shows NaN.

I don't know what to modify, so it also counts up to 10,000,000 and not only works with 10000000.

$('.counter').each(function() {
  var $this = $(this),
    countTo = $this.attr('data-count');

  $({
    countNum: $this.text()
  }).animate({
    countNum: countTo
  }, {
    duration: 8000,
    easing: 'linear',
    step: function() {
      $this.text(Math.floor(this.countNum));
    },
    complete: function() {
      $this.text(this.countNum);
      //alert('finished');
    }
  });
});
body {
  background-color: #F46A6A;
  color: #fff;
  max-width: 800px;
  margin: 100px auto 0;
  text-align: center;
  display: table;
}

.counter {
  display: table-cell;
  margin: 1.5%;
  font-size: 50px;
  background-color: #FF6F6F;
  width: 200px;
  border-radius: 50%;
  height: 200px;
  vertical-align: middle;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="counter" data-count="150">0</div>
<div class="counter" data-count="85">0</div>
<div class="counter" data-count="10,000,000">0</div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

1 Answers1

5

To make the number valid you need to remove the commas. You can use replace() to do that:

countTo = $this.attr('data-count').replace(/,/g, '');

I want "10,000,000" to be displayed actually. It should count to "10,000,000" and output "10,000,000"

In that case you can use the function from this question to format the number within the output from step and complete:

$('.counter').each(function() {
  var $this = $(this),
    countTo = $this.attr('data-count').replace(/,/g, '');

  $({
    countNum: $this.text()
  }).animate({
    countNum: countTo
  }, {
    duration: 8000,
    easing: 'linear',
    step: function() {
      $this.text(numberWithCommas(Math.floor(this.countNum)));
    },
    complete: function() {
      $this.text(numberWithCommas(this.countNum));
    }
  });
});

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
body {
  background-color: #F46A6A;
  color: #fff;
  max-width: 800px;
  margin: 100px auto 0;
  text-align: center;
  display: table;
}

.counter {
  display: table-cell;
  margin: 1.5%;
  font-size: 50px;
  background-color: #FF6F6F;
  width: 200px;
  border-radius: 50%;
  height: 200px;
  vertical-align: middle;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="counter" data-count="150">0</div>
<div class="counter" data-count="85">0</div>
<div class="counter" data-count="10,000,000">0</div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339