This JavaScript code snippet helps you to create counter animation. It adds an event listener to the document object that triggers a function when the DOM is fully loaded. The function defines a counter that takes in four parameters: id, start, end, and duration. The counter function increments the value of the HTML element with the given id from the start value to the end value over the specified duration.
The code then calls the counter function with different parameters for three different HTML elements (“count1”, “count2”, and “count3”) to create three different counters that count up or down to different end values over different durations.
How to Create JavaScript Counter Animation
First of all, load the following assets into the head tag of your HTML document.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css"> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css'>
Create the HTML structure for the counter animation as follows:
<section class="bg-dark text-white py-5 min-vh-100">
<div class="container">
<div class="row justify-content-center text-center">
<div class="col-12">
<h1 class="pb-3">Number counter animation in pure JavaScript</h1>
</div>
<div class="col-md-4">
<span id="count1" class="display-4"></span>
</div>
<div class="col-md-4">
<span id="count2" class="display-4"></span>
</div>
<div class="col-md-4">
<span id="count3" class="display-4"></span>
</div>
</div>
</div>
</section>
Finally, add the following JavaScript function for its functionality:
document.addEventListener("DOMContentLoaded", () => {
function counter(id, start, end, duration) {
let obj = document.getElementById(id),
current = start,
range = end - start,
increment = end > start ? 1 : -1,
step = Math.abs(Math.floor(duration / range)),
timer = setInterval(() => {
current += increment;
obj.textContent = current;
if (current == end) {
clearInterval(timer);
}
}, step);
}
counter("count1", 0, 400, 3000);
counter("count2", 100, 50, 2500);
counter("count3", 0, 40, 3000);
});
That’s all! hopefully, you have successfully created the JavaScript counter animation. If you have any questions or suggestions, feel free to comment below.
