Search code examples
javascriptcsstemplatestransitionsvelte

Transitions with Await in Svelte


Consider this svelte code

   {#await}
   <div class='loading'>
     <p>LOADING LOGO ANIMATION</p>
   </div>  
   {:then value}
   <div class='loaded'>
     <p>Main site content</p>
   </div> 

I'd like to add a transition or animation from the loading 'await' part to when everything is loaded. I'd like the loading part to fade out, and only when its fully faded out for the loaded content to then fade in. Any ideas ? Can this be done this way ?


Solution

  • Sounds like you might be interested in Svelte's transition events.

    Try something like:

    {#await promise}
      <p transition:fade
         on:introstart="{() => visible = false}"
         on:outroend="{() => visible = true}">
      ...waiting </p>
    {:then value}
      {#if visible}
        <div class="loaded" in:fade>
          <p>Main site content</p>
        </div>
      {/if}
    {/await}
    

    Just make sure your <script> imports fade: import { fade } from 'svelte/transition' and you set a variable like visible to false

    Here's a version of this running in a REPL