Web counter display JavaScript

Create a counter display on the web

·

2 min read

Table of contents

Hi!

In this post I will show how to create web counter display. On some websites you can see section where companies show how many satisfied customers they have or products sold. And it looks like web page is calculating this on the go so when you load it it will go from 0 to programmed number.

So how to create something like this.

HTML

Here I will only need two divs as a markup to display it.

<div class="counter-wrap">
    <div class="counter">0</div>
    &nbsp; Satisfied customers.
  </div>

CSS

And to make it look a bit better.

.counter-wrap{
  display: flex;
  width: fit-content;
  font-size: 2rem;
  font-family: Arial, Helvetica, sans-serif;
  margin: 50px;
  padding: 20px 50px;
  border-radius: 50px;
  background-color: rgb(118, 235, 137);
}

JS

We will need three variables, counter container, target and counter.

let counter_container = document.querySelector('.counter')
let counter = 0
let target = 15678

Now we make sure our display function is called when our window is loaded.

window.onload = () => updateCounter()

Lastly we create updateCounter function.

Here we will create recursive function that will handle our display. First we check if counter is smaller from our target. If it is we proceed to calculations.

To speed our number display we will divide the target by any desired number. Smaller the number it will be displayed quicker.

Next we only need to update our container and call our function again with small delay.

const updateCounter = () =>{
  if(counter < target){
    counter += Math.floor(target / 200)    
    document.querySelector('.counter').innerHTML = counter
    setTimeout(updateCounter,1)
  }
}

If you find any mistakes or you have ideas how to refactor my solutions to be simpler/ better please let me know :)

Did you find this article valuable?

Support Chris by becoming a sponsor. Any amount is appreciated!