Display a number progressively on a counter with JavaScript
When we have numerical data to display, we often present them with a fade effect and without animation. However, creating an animation that progressively displays the final number is very simple to achieve and will make your numbers more engaging! Let's see how to do it in this article.
Step 1
Let's start by inserting the libraries into the HTML code.
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Counter-Up/1.0.0/jquery.counterup.min.js"></script>
</head>
We will use the libraries jQuery, Waypoints, and Counter-Up to create this animation.
Step 2
The HTML code.
<div class="counter">
<div class="box">
<i class="fas fa-user-graduate"></i>
<div class="num">25,578</div>
Graduated Students
</div>
</div>
We will place the number we want to display progressively in the .num
class.
Attention: We cannot include spaces; otherwise, the animation will no longer work.
Step 3
Style the
.counter
and.num
classes.
.counter-sec{
padding: 80px 0;
width: 100%;
background: #131416;
position: absolute;
top: 50%;
width: 100%;
transform: translateY(-50%);
}
.num{
font-size: 40px;
margin: 20px 0;
}
Step 4
Style the .box
class and the icon.
.box{
flex: 1;
text-align: center;
padding: 20px;
color: #fff;
text-transform: uppercase;
}
.box i{
font-size: 40px;
color: #333;
}
Step 5
Managing the animation in JavaScript.
$(document).ready(function(){
$('.num').counterUp({
time: 1200
});
});
We will use jQuery to wait for the page to load, then we will use Counter-Up to create the animation. time will be the duration the animation takes to display the final number.