I need a simple JavaScript counter that starts counting from 0 on page load, and counts up to a number defined in HTML.
Here is the jQuery version... how can I do the same thing with plain JavaScript?
$('.count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="count">200</span>%
Ignoring the easing, you can create a simple linear counter using window.requestAnimationFrame
let start // set on the first step to the timestamp provided
const el = document.getElementById('count') // get the element
const final = parseInt(el.textContent, 10) // parse out the final number
const duration = 4000 // duration in ms
const step = ts => {
if (!start) {
start = ts
}
// get the time passed as a fraction of total duration
let progress = (ts - start) / duration
el.textContent = Math.floor(progress * final) // set the text
if (progress < 1) {
// if we're not 100% complete, request another animation frame
requestAnimationFrame(step)
}
}
// start the animation
requestAnimationFrame(step)
<span id="count">200</span>%
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With