Skip to content

Instantly share code, notes, and snippets.

@inorganik
Last active August 19, 2023 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inorganik/85a66941ab88cc10c5fa5b26aead5f2a to your computer and use it in GitHub Desktop.
Save inorganik/85a66941ab88cc10c5fa5b26aead5f2a to your computer and use it in GitHub Desktop.
CountUp.js with Svelte!
<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