Animated Count Up – alternative to CountUp.js

Occasionally a project requires some stats to show off and there is no better way than by adding a little animation to the number values.

Historically I would use a script like CountUp.js but on a few projects I used that on, ran into a few issues that needed attention to avoid console errors depending on how they worked with scrolling actions of the user.

On a current project I’m working on that needed animating count up values, I decided to use something else, nameley jQuery for the counting value animation, and Waypoints.js for triggering this when the elements come into view from scrolling.

The only 3rd party we need (other than jQuery) is Waypoints 4.0.1:

wp_enqueue_script( 'waypoints', 'https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js', array(), _S_VERSION, true );

Here’s a stripped down version of what I wrote:

<div class="col-sm-12 col-md-6 col-lg-3">
<div class="stat-inner text-center">
<div class="icon-holder">
<div class="stat-icon-inner">
<div class="value">
<div class="counterholder">
<span class="counter" data-count="12000"></span>
</div>
</div>
</div>
</div>
</div>
</div>

Here, the 12000 is the value we are counting up to. In reality, I used a repeater to have 4 stats on the same row, along with other date like a title, label, description and icon. But this is a stripped down version so have omitted that to keep things simple.

Next, we need the jQuery:

var waypoint = new Waypoint({
element: document.getElementById('counter'),
handler: function() {
$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({
countNum: $this.text()
}).animate({
countNum: countTo
},
{
duration: 3000, // time it takes to count up
easing: 'linear',
step: function() {
$this.text(commaSeparateNumber(Math.floor(this.countNum)));
},
complete: function() {
$this.text(commaSeparateNumber(this.countNum));
}
}
);
});
function commaSeparateNumber(val) {
while (/(\d+)(\d{3})/.test(val.toString())) {
val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
}
return val;
}
},
offset: '100%' // this triggers the animation when it hits the bottom of the viewport.
})

And voila, you have an animated counter that triggers when the elements are in view.

Useful post? Share it

Leave a Reply

Your email address will not be published. Required fields are marked *