Skip to content

Instantly share code, notes, and snippets.

@vkartk
Created September 4, 2021 18:30
Show Gist options
  • Save vkartk/afc4f040ee97dd56778c15cff929daa7 to your computer and use it in GitHub Desktop.
Save vkartk/afc4f040ee97dd56778c15cff929daa7 to your computer and use it in GitHub Desktop.
Animated counter in Vanilla JS
<script>
const counters = document.querySelectorAll(".count");
const speed = 200;
counters.forEach((counter) => {
const updateCount = () => {
const target = parseInt(+counter.getAttribute("data-target"));
const count = parseInt(+counter.innerText);
const increment = Math.trunc(target / speed);
console.log(increment);
if (count < target) {
counter.innerText = count + increment;
setTimeout(updateCount, 1);
} else {
count.innerText = target;
}
};
updateCount();
});
</script>
// Sample Code :
// <h1 data-target="16000" class="count">0</h1>
// <p data-target="8000" class="count">0</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment