On a site I have a number counter that always increases, without any fancy animation. Now I need to animate it every time the number updates, like this:
Which HTML (+CSS +JS if needed) code can I use for this? Thanks!
P.S.: The number has 2 decimals and uses "," as a decimal separator.
function animateNumber(from, to, duration) {
let start = new Date().getTime();
let timer = setInterval(function() {
let now = new Date().getTime();
let timePassed = now - start;
if (timePassed >= duration) {
clearInterval(timer);
timePassed = duration;
}
let progress = timePassed / duration;
let result = Math.floor((to - from) * progress + from * 100) / 100;
document.getElementById('number').textContent = result.toFixed(2).replace('.', ',');
if (progress === 1) clearInterval(timer);
}, 10);
}
// Example usage:
animateNumber(0, 1234.56, 2000); // Change 1234.56 to your desired number and 2000 to the duration in milliseconds
This code will create a counter with a specified starting number (0 in this case) and animate it to a specified ending number (1234.56 in this case) over a specified duration (2000 milliseconds in this case).
You can adjust the HTML, CSS, and JavaScript code as needed to fit your specific requirements and styling preferences.
const el = document.querySelector('.odometer')
const od = new Odometer({
el: el,
value: 1234, // default value
// Any option (other than auto and selector) can be passed in here
format: '( ddd),dd',
theme: 'default',
duration: 3000,
})
// change to new value
od.update(9876)
// or
el.innerHTML = 9876
2
Answers
You can achieve this effect using HTML, CSS, and JavaScript. Here’s a simple example:
HTML:
CSS:
JavaScript:
This code will create a counter with a specified starting number (0 in this case) and animate it to a specified ending number (1234.56 in this case) over a specified duration (2000 milliseconds in this case).
You can adjust the HTML, CSS, and JavaScript code as needed to fit your specific requirements and styling preferences.
You can have basic concept from this : https://www.geeksforgeeks.org/how-to-make-animated-counter-using-javascript/
According to the illustration, this already unmaintained library came to mind:
Example