50projectsIn50days – Day 15: Counter
A page which load three values that are hardcoded in the HTML tag:
<div class="counter-container">
<i class="fa-solid fa-truck-fast fa-3x"></i>
<div class="counter" data-target="120000"></div>
<span>Packages Delivered</span>
</div>
<div class="counter-container">
<i class="fa-solid fa-money-bill fa-3x"></i>
<div class="counter" data-target="500000"></div>
<span>Dollars of revenue</span>
</div>
<div class="counter-container">
<i class="fa-solid fa-handshake fa-3x"></i>
<div class="counter" data-target="7500"></div>
<span>Deals Closed</span>
</div>
Each one with a class “counter” will be selected and for each one an inner text will be added as Zero and will be aded an increment up to the target (which is located in the data-target) is reached:
const counter = document.querySelectorAll('.counter')
counter.forEach(counter => {
counter.innerText = '0'
const updateCounter = () => {
const target = +counter.getAttribute('data-target')
const c = +counter.innerText
const increment = target / 200
if(c < target){
counter.innerText = `${Math.ceil(c + increment)}`
setTimeout(updateCounter, 1)
} else {
counter.innerText = target
}
}
updateCounter()
})
The functions call itself at the end.
You can see the code in this GitHub Repository: 15.counter and the demo of the project is here: Counter