Last active
August 19, 2023 13:23
-
-
Save inorganik/85a66941ab88cc10c5fa5b26aead5f2a to your computer and use it in GitHub Desktop.
CountUp.js with Svelte!
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
<script> | |
/** | |
* You can use CountUp directly like this: | |
*/ | |
import { onMount } from 'svelte'; | |
import { CountUp } from 'countup.js'; | |
let targetEl, countUpAnim | |
onMount(() => { | |
countUpAnim = new CountUp(targetEl, 7000) | |
}) | |
/** | |
* OR, if you just need a simple animation, you can bypass CountUp altogether | |
* and use svelte's built-in animation abilities: | |
*/ | |
import { tweened } from 'svelte/motion' | |
import { quintOut } from 'svelte/easing' | |
import { derived } from 'svelte/store' | |
let myNumber = tweened(0, { duration: 2000, easing: quintOut }) | |
let formatted = derived(myNumber, ($myNumber) => $myNumber.toFixed()) | |
</script> | |
<!-- With CountUp --> | |
<h1 bind:this={targetEl}>0</h1> | |
<button on:click={() => countUpAnim.start()}>Count with CountUp!</button> | |
<button on:click={() => countUpAnim.reset()}>Reset</button> | |
<!-- With just Svelte --> | |
<h1>{$formatted}</h1> | |
<button on:click={() => myNumber.set(2500)}>Count with Svelte motion!</button> | |
<button on:click={() => myNumber.set(0, { duration: 0 })}>Reset</button> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment