Created
September 4, 2021 18:30
-
-
Save vkartk/afc4f040ee97dd56778c15cff929daa7 to your computer and use it in GitHub Desktop.
Animated counter in Vanilla JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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