This simple Svelte component shows a button that toggles a message. The message uses a fade transition to appear and disappear smoothly. It also includes accessibility features like aria-pressed and keyboard focus.
Svelte
<script>
import { fade } from'svelte/transition';
let visible = false;
</script>
<button on:click={() => visible = !visible} aria-pressed={visible} aria-label="Toggle message">
Toggle Message
</button>
{#if visible}
<p transition:fade tabindex="0">Hello! This message fades in and out smoothly.</p>
{/if}
OutputSuccess
Important Notes
Transitions help users follow changes without confusion.
Keep transitions short and smooth to avoid delays.
Always consider accessibility: ensure keyboard users and screen readers can still interact well.
Summary
Transitions make UI changes feel natural and clear.
Use them when showing, hiding, or updating content.
Svelte makes adding transitions easy with simple syntax.
Practice
(1/5)
1. Why do transitions improve user experience in Svelte applications?
easy
A. They make UI changes feel smooth and clear to users.
B. They increase the app's loading speed significantly.
C. They automatically fix bugs in the code.
D. They reduce the app's file size drastically.
Solution
Step 1: Understand the purpose of transitions
Transitions help make changes in the user interface feel smooth and natural, improving clarity.
Step 2: Compare other options
Options about loading speed, bug fixing, or file size are unrelated to transitions' main role.
Final Answer:
They make UI changes feel smooth and clear to users. -> Option A
Quick Check:
Transitions enhance clarity and smoothness = D [OK]
4. Identify the error in this Svelte code that prevents the transition from working:
<script>
import { fade } from 'svelte/transition';
let show = true;
</script>
{#if show}
<div transition=fade>Content</div>
{/if}
<button on:click={() => show = !show}>Toggle</button>
medium
A. The transition directive syntax is incorrect; it should be transition:fade.
B. The variable 'show' is not initialized properly.
C. The import statement for fade is missing.
D. The button click handler syntax is invalid.
Solution
Step 1: Check transition directive syntax
The correct syntax uses a colon: transition:fade, not transition=fade.
Step 2: Verify other parts
The variable 'show' is initialized, fade is imported, and button syntax is valid.
Final Answer:
The transition directive syntax is incorrect; it should be transition:fade. -> Option A
Quick Check:
Correct transition syntax uses colon = B [OK]
Hint: Use colon in transition directive: transition:fade [OK]
Common Mistakes:
Using '=' instead of ':' in transition directive
Assuming variable initialization is wrong
Missing import statement
Incorrect button event syntax
5. You want to add a slide transition that lasts 500ms when a component appears or disappears. Which Svelte code snippet correctly applies this with accessibility in mind?