0
0
Svelteframework~30 mins

Named actions in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Named Actions in Svelte
📖 Scenario: You are building a simple interactive web page where you want to add a special effect to an HTML element when the user interacts with it.Using Svelte's named actions, you will create a reusable action that changes the background color of a box when the mouse enters and leaves it.
🎯 Goal: Build a Svelte component that uses a named action called highlight to change the background color of a <div> when hovered.
📋 What You'll Learn
Create a named action function called highlight that changes the background color of an element.
Add a configuration variable color to specify the highlight color.
Use the highlight action on a <div> element with the configured color.
Ensure the highlight effect is removed when the mouse leaves the element.
💡 Why This Matters
🌍 Real World
Named actions in Svelte help you add reusable interactive behaviors to elements, such as animations, event handling, or DOM manipulations, without repeating code.
💼 Career
Understanding named actions is important for building clean, maintainable Svelte applications and is a common skill required for frontend developer roles using Svelte.
Progress0 / 4 steps
1
Create the highlight named action function
Write a named action function called highlight that takes an element parameter and adds event listeners for mouseenter and mouseleave. On mouseenter, set the element's background color to yellow. On mouseleave, reset the background color to '' (empty string).
Svelte
Hint

Remember, a named action is a function that receives the element and can return an object with a destroy method to clean up event listeners.

2
Add a color configuration variable
Add a variable called color and set it to the string 'lightblue'. This variable will be used to customize the highlight color in the next step.
Svelte
Hint

Define color outside the highlight function and use it inside onMouseEnter to set the background color.

3
Use the highlight action on a <div>
In the Svelte component, create a <div> element with the text Hover over me!. Use the use:highlight directive on this <div> to apply the highlight action.
Svelte
Hint

Use the use:highlight directive on the <div> element to apply the action.

4
Make the highlight color configurable via action parameter
Modify the highlight action to accept a second parameter params with a color property. Use params.color as the highlight color instead of the fixed color variable. Update the <div> to pass { color: 'pink' } as the parameter to use:highlight.
Svelte
Hint

Accept params as the second argument and use params.color inside the action. Pass the color object in the use:highlight directive.