Currently, I am immersed in a web project that involves incrementation animations. To achieve this, I have devised a counter function similar to the one shown below:
const counters = document.querySelectorAll('.counter');
counters.forEach(counter => {
const updateCount = () => {
const target = +counter.getAttribute('data-target');
const count = +counter.innerText;
const speed = target / 1000; //this will not work accurate if using Math.ceil or floor to round number up
if (count < target) {
counter.innerText = count + speed;
setTimeout(updateCount,1);
} else {
counter.innerText = target;
}
}
updateCount();
});
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html , body {
width: 100%;height: 100%;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
/* HEADER */
.counter {
font-size: 20px;
font-weight: bold;
padding: 5px;
}
<span data-target="20" class="counter">0</span>
<span data-target="100" class="counter">0</span>
<span data-target="50" class="counter">0</span>
<span data-target="250000" class="counter">0</span>
The challenge lies in the fact that the numbers displayed on the website are in decimal format. Various attempts such as math.ceil
,math.floor
, ... were made to rectify this issue but they interfered with the speed
of the counter. Is there any method to solely display the integer portion WITHOUT affecting the speed
?