How to Make Animated Counter Using jQuery

In this tutorial I will show you how to implement a custom animated counter using just html css and jquery, no plugin. To achieve this functionality we will have to get the jquery library and add it to the website, and create 3 new files. index.html, style.css and main.js

Animated Counter Using jQuery steps:

First of all we will have to create the HTML structure which will be used to create the counter and then we will animate it using jquery. Just copy paste the following HTML structure in your index.html file.

<div id="counter">
    <div class="counter-value" data-count="300">0</div>
    <div class="counter-value" data-count="400">100</div>
    <div class="counter-value" data-count="1500">200</div>
</div>

As you can see we added the desired value in the data-count attribute. Next in jquery we will check when you scroll down until you reach the section. If the section is in viewport we will have to animate the numbers to increase to the value which is in the data-count attribute. To do that we will add the following code in main.js file, we just created.

var a = 0;
$(window).scroll(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: 2000,
          easing: 'swing',
          step: function() {
            $this.text(Math.floor(this.countNum));
          },
          complete: function() {
            $this.text(this.countNum);
            //alert('finished');
          }

        });
    });
    a = 1;
  }

});

That's all the code we need to do this functionality, test it and let me know if this worked for you. The next step is to customize the counter as you wish. To do that open your style.css file and start design your counter as you wish. To test better this script you should add margin-top to body at least 1000px because you will have to scroll in order to find out if the functionality is really working.

0 0 votes
Article Rating
Subscribe
Notify of
guest
6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Shaggy
Shaggy
4 years ago

This is the best article I found on the internet on this topic.

Vineet Thakur
Vineet Thakur
4 years ago

It didn’t worked for me. Numbers appeared as standstill 🙁

Alberto
Alberto
3 years ago
Reply to  Vineet Thakur
Echo
Echo
3 years ago
Reply to  Vineet Thakur

You have to call to the jQuery library. That’s what they didn’t tell you here.

Marek
Marek
4 years ago

Working, thanks 😉

Echo
Echo
3 years ago

I wish I knew how to make this countdown. Dang! I need to go from 100 to 1 but only initiate when the user is scrolling near

6
0
Would love your thoughts, please comment.x
()
x