I was trying to make separate counters with separate increments, but it won't work. The code I now have works but the 3 counters have the same increment. My question is how can I code it so every counter has its own increment (and keeping it DRY).
const counter = function() {
const counters = document.querySelectorAll(".counter");
counters.forEach((counter) => {
function updateCounter() {
const target = +counter.getAttribute("data-target");
const c = +counter.innerText;
const increment = target / 500;
if (c < target) {
counter.innerText = `${Math.ceil(c + increment)}`;
setTimeout(updateCounter, 1);
} else {
counter.innerText = target;
}
}
updateCounter();
});
}
counter();
<div class="counter" data-target="6"></div>
<div class="counter" data-target="6000"></div>
<div class="counter" data-target="12000"></div>
Hope you guys can help me out. :)
Thanks in advance!