JQuery Animate function not working commas/decimals

248 views Asked by At

Here is my HTML:

<li class="mega-menu-counter mega-menu-item mega-menu-item-type-post_type mega-menu-item-object-page mega-align-bottom-left mega-menu-flyout mega-menu-item-12028 menu-counter" id="mega-menu-item-12028">
   <a class="mega-menu-link" href="https://createandgo.com/blog-income-report/" tabindex="0">August 2019 <div>$<span class="counter">111,926.06</span></div><div>Blog Income Report</div></a>
</li>

And here is my JavaScript:

<script>
$('.Count').each(function () {
  var $this = $(this);
  jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
    duration: 1000,
    easing: 'swing',
    step: function () {
      $this.text(this.Counter.toFixed(2));
    }
    }
  });
});
</script>

I have the following resources loading in the head of my site:

<script
  src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-animateNumber/0.0.14/jquery.animateNumber.min.js"></script>

Can someone tell me why the counter isn't working?enter image description here

1

There are 1 answers

0
User863 On
  • replace(/,/g, '') - converts currency format to number format

  • toLocaleString(...) - converts number to currency format

$('.count').each(function() {
  var $this = $(this);
  jQuery({
    Counter: 0
  }).animate({
    Counter: $this.text().replace(/,/g, '')
  }, {
    duration: 1000,
    easing: 'swing',
    step: function() {
      $this.text(toCurrencyFromat(this.Counter));
    },
    complete: function() {
      $this.text(toCurrencyFromat(this.Counter));
    }
  });
});

function toCurrencyFromat(num) {
  return (num).toLocaleString('en-US', {
    currency: 'USD',
    maximumFractionDigits: 2
  })
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-animateNumber/0.0.14/jquery.animateNumber.min.js"></script>

<li class="mega-menu-counter mega-menu-item mega-menu-item-type-post_type mega-menu-item-object-page mega-align-bottom-left mega-menu-flyout mega-menu-item-12028 menu-counter" id="mega-menu-item-12028">
  <a class="mega-menu-link" href="https://createandgo.com/blog-income-report/" tabindex="0">August 2019 <div>$<span class="count counter">111,926.06</span></div><div>Blog Income Report</div></a>
</li>