0
0
Svelteframework~5 mins

In and out transitions in Svelte

Choose your learning style9 modes available
Introduction

In and out transitions help make elements appear and disappear smoothly on the screen. They make your app feel friendly and alive.

Showing a message that fades in and out when a button is clicked.
Making a menu slide in when opened and slide out when closed.
Displaying images that zoom in when they appear and zoom out when removed.
Animating notifications that pop up and then vanish after a few seconds.
Syntax
Svelte
<div in:transitionName out:transitionName>Content</div>
Replace transitionName with the name of a built-in or custom transition like fade or slide.
You can customize transitions by adding parameters inside curly braces, e.g., in:fade={{ duration: 500 }}.
Examples
This example shows a paragraph that fades in when it appears and fades out when it disappears.
Svelte
<script>
  import { fade } from 'svelte/transition';
  let visible = true;
</script>

<button on:click={() => visible = !visible}>Toggle</button>

{#if visible}
  <p in:fade out:fade>Hello!</p>
{/if}
This example uses the slide transition with a custom duration to animate a menu appearing and disappearing.
Svelte
<script>
  import { slide } from 'svelte/transition';
  let show = false;
</script>

<button on:click={() => show = !show}>Show Menu</button>

{#if show}
  <nav in:slide={{ duration: 300 }} out:slide={{ duration: 300 }}>
    <ul>
      <li>Home</li>
      <li>About</li>
      <li>Contact</li>
    </ul>
  </nav>
{/if}
Sample Program

This component toggles a message with a fade-in and slide-out effect. The button updates its label and accessibility attributes. The message is keyboard focusable for accessibility.

Svelte
<script>
  import { fade, slide } from 'svelte/transition';
  let showMessage = false;
</script>

<button on:click={() => showMessage = !showMessage} aria-pressed={showMessage} aria-label="Toggle message">
  {showMessage ? 'Hide' : 'Show'} Message
</button>

{#if showMessage}
  <p in:fade={{ duration: 400 }} out:slide={{ duration: 600 }} tabindex="0">
    Welcome to Svelte transitions!
  </p>
{/if}
OutputSuccess
Important Notes

Always use semantic HTML and ARIA attributes for better accessibility.

Transitions can be combined or customized with parameters like duration, delay, and easing.

Use keyboard navigation to test if elements are focusable and transitions do not interfere.

Summary

In and out transitions animate elements entering and leaving the page.

Use in: and out: directives with built-in transitions like fade and slide.

Customize transitions with parameters for smooth, friendly user experiences.