Skip to content
Advertisement

How to create a number counter for multiple elements with JS?

I am trying to create a counter from 0 to the innerHTML number value. I had it working for the first element but can’t figure out how to apply the event across multiple number elements

function animateValue(id, start, end, duration) {
    var range = end - start;
    var current = start;
    var increment = end > start? 1 : -1;
    var stepTime = Math.abs(Math.floor(duration / range));
    var obj = document.querySelectorAll(id);
    var end = obj.innerHTML;
    var timer = setInterval(function() {
        current += increment;
        obj.innerHTML = current;
        if (current == end) {
            clearInterval(timer);
        }
    }, stepTime);
}

animateValue("value", 0, 3000);
.value {
    font-size: 50px;
}
<div class="value">244</div>
<div class="value">64,244</div>
<div class="value">1,100,244</div>

Advertisement

Answer

In JavaScript, you can not make changes to multiple elements without iterating. So, you gotta call the animateValue function, for each .value element. start would generally be zero, so you can make it as last parameter, and give it default value. And in place of innerHTML, make use of innerText. Both will work, but they have their roles.

function animateValue(item, duration, start = 0) {
  var end = item.innerText.replaceAll(",", "").trim();
  var range = end - start;
  var increment = (range / (duration / 10));
  
  if(end < start){
    increment *= -1;
  }
  var current = start;
  var stepTime = 1;
  
  var timer = setInterval(function() {
    current += Math.ceil(increment);
    item.innerText = current;
    if (current >= end) {
      item.innerText = end;
      clearInterval(timer);
    }
  }, stepTime);
}

document.querySelectorAll('.value').forEach((item)=>{
  animateValue(item, 3000);
});
.value {
  font-size: 50px;
}
<div class="value">244</div>
<div class="value">1,624</div>
<div class="value">1,100,244</div>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement