1

So, I found this cool pen Creative Animated Counter on Scroll but I want to know how to format the numbers so they have a comma if it's over a thousand.

function visible(partial) {
  var $t = partial,
    $w = jQuery(window),
    viewTop = $w.scrollTop(),
    viewBottom = viewTop + $w.height(),
    _top = $t.offset().top,
    _bottom = _top + $t.height(),
    compareTop = partial === true ? _bottom : _top,
    compareBottom = partial === true ? _top : _bottom;

  return ((compareBottom <= viewBottom) && (compareTop >= viewTop) && $t.is(':visible'));
}

$(window).scroll(function() {
  if (visible($('.count-digit'))) {
    if ($('.count-digit').hasClass('counter-loaded')) return;
    $('.count-digit').addClass('counter-loaded');

    $('.count-digit').each(function() {
      var $this = $(this);
      jQuery({
        Counter: 0
      }).animate({
        Counter: $this.text()
      }, {
        duration: 5000,
        easing: 'swing',
        step: function() {
          $this.text(Math.ceil(this.Counter));
        }
      });
    });
  }
})
Roy Scheffers
  • 3,588
  • 10
  • 31
  • 35
ChubbyTio
  • 13
  • 3
  • 1
    With the provided duplicated question, you can use the accepted answer and change the following line: `$this.text(Math.ceil(this.Counter));`. Hope it helps! – Karl-André Gagnon Aug 29 '18 at 15:16
  • Try this $this.text(Math.ceil(this.Counter).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")); – Vermicello Aug 29 '18 at 15:18

1 Answers1

0

The method you're looking for is toLocaleString. You can invoke this on a number to get the commas you're looking for. You would just need to change your step function like so:

step: function() {
  $this.text(Math.ceil(this.Counter).toLocaleString());
}
kamoroso94
  • 1,618
  • 1
  • 19
  • 19