Skip to content

Instantly share code, notes, and snippets.

@Saoming
Last active August 3, 2023 16:28
Show Gist options
  • Save Saoming/58eec3caef92e0a2ece4e781317d471e to your computer and use it in GitHub Desktop.
Save Saoming/58eec3caef92e0a2ece4e781317d471e to your computer and use it in GitHub Desktop.
Animated Counter with Alpine JS
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