📖 Scenario: You are building a simple Svelte app where a message appears and disappears with a smooth custom animation. This helps make the app feel lively and friendly.
🎯 Goal: Create a Svelte component that shows a message with a custom fade and slide transition when it appears and disappears.
📋 What You'll Learn
Create a boolean variable visible to control message visibility
Create a custom transition function called fadeSlide
Use the transition:fadeSlide directive on the message element
Add a button to toggle the visible variable
💡 Why This Matters
🌍 Real World
Custom transitions make web apps feel more dynamic and polished by animating elements smoothly when they appear or disappear.
💼 Career
Knowing how to create and apply custom transitions is valuable for frontend developers to improve user experience and interface polish.
Progress0 / 4 steps
1
DATA SETUP: Create a visible variable
Create a boolean variable called visible and set it to true inside the <script> tag.
Svelte
Hint
Use let visible = true; inside the <script> tag.
2
CONFIGURATION: Create a custom transition function fadeSlide
Inside the <script> tag, create a function called fadeSlide that takes a parameter node and returns an object with duration: 400 and a css function that returns a string combining opacity and transform: translateX based on t. Use t to fade from 0 to 1 and slide from 20px to 0px.
Svelte
Hint
Define fadeSlide returning an object with duration and css properties. Use t to control opacity and horizontal slide.
3
CORE LOGIC: Use the fadeSlide transition on the message
Add the directive transition:fadeSlide to the <p> element inside the {#if visible} block.
Svelte
Hint
Use transition:fadeSlide on the <p> tag.
4
COMPLETION: Add a button click to toggle visible
Add an on:click event to the <button> that toggles the visible variable using visible = !visible.
Svelte
Hint
Add on:click={() => visible = !visible} to the <button> tag.
Practice
(1/5)
1. What is the main purpose of a custom transition in Svelte?
easy
A. To create unique animations when elements enter or leave the page
B. To fetch data from an API
C. To manage component state
D. To handle user input events
Solution
Step 1: Understand what transitions do in Svelte
Transitions animate elements as they appear or disappear from the DOM.
Step 2: Identify the role of custom transitions
Custom transitions let you define your own animation styles for these changes.
Final Answer:
To create unique animations when elements enter or leave the page -> Option A