Jump to content

Animated number counter

Recommended Posts

Site URL: https://www.meetwo.co.uk/impact-test

I'm trying to add animated numbers to my site. When the page loads the numbers will automatically count up to a maximum over a specified duration. I've found a bit of code that has been mentioned elsewhere on the forum and that's working well (see code below). Now I would like to improve this by adding a comma separation in the numbers eg 23,500. Stack Overflow offer some methods for adding commas but I can't get any of them to work. Any help would be much appreciate. Thanks

Main code

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
var a = 0;
$(window).load(function() {

  var oTop = $('#counter').offset().top - window.innerHeight;
  if (a == 0 && $(window).scrollTop() > oTop) {
    $('.counter-value').each(function() {
      var $this = $(this),
        countTo = $this.attr('data-count');
      $({
        countNum: $this.text()
      }).animate({
          countNum: countTo
        },
        {
          duration: 3000,
          easing: 'swing',
          step: function() {
            $this.text(Math.floor(this.countNum));
          },
          complete: function() {
            $this.text(this.countNum);
          }
        });
    });
    a = 1;
  }
});
</script>
<div id="counter">
    <div class="sqs-col sqs-col-4 counter-value" data-count="30000" data-desc="Young people">0</div>
  <div class="sqs-col sqs-col-4 counter-value" data-count="80000" data-desc="Problems">0</div>
  <div class="sqs-col sqs-col-4 counter-value" data-count="250000" data-desc="Solutions">0</div>
</div>
 

Link to comment
  • 2 months later...
  • Replies 3
  • Views 3.6k
  • Created
  • Last Reply

Thanks for sharing this script. I got the commas to work by adding a .toLocaleString() modifier in two places near the end of your counter function call:

$this.text(Math.floor(this.countNum).toLocaleString());

and

$this.text(this.countNum.toLocaleString())

Now the numbers have comma separators while counting up, and the final display number also has a comma(s) as needed.

Link to comment
  • 2 months later...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Squarespace Webinars

Free online sessions where you’ll learn the basics and refine your Squarespace skills.

Hire a Designer

Stand out online with the help of an experienced designer or developer.