TechSolutionsHere.com

How To Create An Animated Counter With JavaScript Only!!

We often use some large jquery plugin to create number Counter in our html template though we can do that without any plugin. Let’s make a on-scroll counter with js.
HTML Code :

<div class="counter-card-wrap">
    <div class="counter-card">
        <span class="counter">100</span>
        <p>Award Winning</p>
    </div>
    <div class="counter-card">
        <span class="counter">64</span>
        <p>Solve Issues</p>
    </div>
    <div class="counter-card">
        <span class="counter">73</span>
        <p>Successful Projects</p>
    </div>
    <div class="counter-card">
        <span class="counter">859</span>
        <p>Happy Customers</p>
    </div>
</div>

Js Code :

// Counter Js
if ("IntersectionObserver" in window) {
    let counterObserver = new IntersectionObserver(function (entries, observer) {
        entries.forEach(function (entry) {
            if (entry.isIntersecting) {
            let counter = entry.target;
            let target = parseInt(counter.innerText);
            let step = target / 200;
            let current = 0;
            let timer = setInterval(function () {
                current += step;
                counter.innerText = Math.floor(current);
                if (parseInt(counter.innerText) >= target) {
                clearInterval(timer);
                }
            }, 10);
            counterObserver.unobserve(counter);
            }
        });
    });

    let counters = document.querySelectorAll(".counter");
        counters.forEach(function (counter) {
        counterObserver.observe(counter);
    });
}

That’s it. you can add some css to beautify the counter.
Happy Coding !!!

 

Exit mobile version