5

What would be the best way to trigger an animation when a reactive variable changes? I would like to do something like this : 

<script>
    import { fade } from 'svelte/transition'
    let count = 0;
    const handleClick = () => count +=1
</script>

<button on:click={handleClick} transition:slide>
    Click me
</button>
<p> You cliked <strong transition:fade>{count}</strong> times</p>

Which doesn't work because the <strong>node isn't removed from the DOM (I guess). So what would be the best way to have numbers fading in and out when they change?

Etienne
  • 163
  • 1
  • 9

1 Answers1

12

You can now (v3.28) use the {#key <key} directive:

<script>
    import { fade } from 'svelte/transition'
    let count = 0;
    const handleClick = () => count +=1
</script>

<button on:click={handleClick}>
    Click me
</button>
<p> You cliked 
    {#key count}
      <strong in:fade>{count}</strong> 
    {/key}
    times</p>

old answer

Try this :

<script>
    import { fade } from 'svelte/transition'
    let count = 0;
    const handleClick = () => count +=1
</script>

<button on:click={handleClick}>
    Click me
</button>
<p> You cliked 
    {#each [count] as c (c)}
    <strong in:fade>{c}</strong> 
    {/each}
    times</p>

REPL

Jérémie B
  • 10,611
  • 1
  • 26
  • 43