0
0
Svelteframework~30 mins

Action parameters in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Action Parameters in Svelte
📖 Scenario: You are building a simple interactive box on a webpage. You want to change the box's background color when the user clicks on it. To do this, you will use a Svelte action that accepts a color parameter.
🎯 Goal: Create a Svelte component with a colored box. Use an action that changes the box's background color based on a parameter passed to the action.
📋 What You'll Learn
Create a Svelte action function named colorChange that accepts a parameter for the color.
Create a color variable with the value 'lightblue'.
Use the colorChange action on a <div> element, passing the color variable as a parameter.
The box should have a fixed size and show the background color from the action parameter.
💡 Why This Matters
🌍 Real World
Actions in Svelte let you add reusable behavior to HTML elements, like changing styles or handling events, which is common in interactive web apps.
💼 Career
Understanding how to use actions with parameters helps you build clean, modular, and accessible UI components in Svelte, a popular modern frontend framework.
Progress0 / 4 steps
1
Create the colorChange action function
Create a Svelte action function called colorChange that takes two parameters: node and color. Inside the function, set the node.style.backgroundColor to the color parameter. Return an object with a destroy method that resets the background color to an empty string.
Svelte
Hint

Remember, a Svelte action is a function that receives the DOM node and parameters. You can set styles directly on the node.

2
Create a color variable
Inside the <script> tag, create a variable called color and set it to the string 'lightblue'.
Svelte
Hint

Use let color = 'lightblue'; inside the script tag.

3
Use the colorChange action on a div
Add a <div> element below the <script> tag. Give it a fixed width and height of 150px using inline styles. Use the use:colorChange directive on the <div> and pass the color variable as the parameter.
Svelte
Hint

Use <div use:colorChange={color} style="width: 150px; height: 150px;"></div>.

4
Add a border and aria-label for accessibility
Add a border style of 2px solid black to the <div> element's inline styles. Also add an aria-label attribute with the value 'Color box' to the <div> for accessibility.
Svelte
Hint

Add border: 2px solid black; to the style and aria-label="Color box" to the div.