Home /

Notes to self /

Counting up, a JS code snippet

Counting up, a JS code snippet

It's a 1 minute read

Working on the ‘UK food data’* website today, and I decided I wanted to have some animated stats on the page.

Basically the stats would show how many establishments we hold data on and how many users we have using the API etc. I thought it would be a nice addition to the site.

So I started work on a simple JS function which I could call rather than relying on ones that are already out there. That said, I may move to using something like inorganik’s countUp, but we shall see how this simple script works out.


Demo

100

550001 total

£845 spent

Simply refresh the page to see the count up in action.


The code

In the HTML we simply add the number to a span with the class of .number.

<p class="text-green"><span class="number">100</span></p>
<p class="text-green"><span class="number">550001</span> total</p>
<p class="text-green">£<span class="number">845</span> spent</p>

For the JS side we take each element using the .number class and we pass that to the JS snippet. We then perform some simple math on the content of the element and step up until we reach the target number.

function countUp(numberElement) {
  let current = 0;
  const total = parseInt(numberElement.textContent);
  const increment = Math.ceil(total / 100);

  function step() {
    current += increment;
    if (current > total) current = total;
    numberElement.textContent = current.toLocaleString();
    (current !== total) && requestAnimationFrame(step);
  }
  step();
}

document.querySelectorAll('.number').forEach(elem => countUp(elem));

There we go, really quick article today. Hopefully it helps someone out, however if you’re after something a bit more in-depth, I’d highly recommend checking out inorganik’s countUp.

* Still a holding name, any ideas?

Privacy Work Terms

© 2021 Alan Reid