Onscreen Counter - JavaScript

PHOTO EMBED

Mon Oct 09 2023 16:49:18 GMT+0000 (Coordinated Universal Time)

Saved by @destinyChuck #html #css #javascript

function incrementStats() {
    const counters = document.querySelectorAll('.counter');

    counters.forEach((counter) => {
        counter.innerText = 0;

        const updateCounter = () => {
            const target = +counter.getAttribute('data-target'); // the "+" here casts the returned text to a number
            const c = +counter.innerText;
            const increment = target / 200;

            if (c < target) {
                counter.innerText = Math.ceil(c + increment);
                setTimeout(updateCounter, 1);
                // here the function is calling itself until "c"
                // reaches the "data-target", making it recursive
            } else {
                counter.innerText = target;
            }
        };

        updateCounter();
    });
}

document.addEventListener('DOMContentLoaded', incrementStats);
content_copyCOPY

This will display a counter, starting (currently set to 0) up to data-target in increments of (data-target / 200), each increment/loop set, via setTimout to 1ms. It first brings in all .counter elements.