Last active
August 3, 2023 16:28
-
-
Save Saoming/58eec3caef92e0a2ece4e781317d471e to your computer and use it in GitHub Desktop.
Animated Counter with Alpine JS
This file contains hidden or 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
document.addEventListener('alpine:init', async () => { | |
// eslint-disable-next-line no-unused-expressions, no-undef | |
Alpine.data('animatedCounter', (target) => ({ | |
current: 0, | |
// eslint-disable-next-line object-shorthand | |
target: target, | |
time: 400, | |
start: 0, | |
updateCounter() { | |
const { start } = this; | |
const increment = (this.target - start) / this.time; | |
const handle = setInterval(() => { | |
if (this.current < this.target) this.current += increment; | |
else { | |
clearInterval(handle); | |
this.current = this.target; | |
} | |
}, 1); | |
}, | |
})); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment