0
0
Svelteframework~30 mins

Why actions add reusable element behavior in Svelte - See It in Action

Choose your learning style9 modes available
Add Reusable Behavior to Elements Using Svelte Actions
📖 Scenario: You are building a simple web page where some elements need a special behavior: they should change their background color when the mouse hovers over them. Instead of writing the same code for each element, you want to create a reusable behavior that you can apply easily to any element.
🎯 Goal: Build a Svelte action that changes the background color of an element on mouse hover and apply it to multiple elements to reuse the behavior.
📋 What You'll Learn
Create a Svelte action named hoverHighlight that changes the background color of an element when hovered
Use the hoverHighlight action on at least two different elements
Ensure the background color returns to normal when the mouse leaves the element
Keep the action reusable and clean
💡 Why This Matters
🌍 Real World
In real websites, you often want to add the same interactive behavior to many elements, like hover effects or tooltips. Svelte actions let you write this behavior once and reuse it easily.
💼 Career
Understanding Svelte actions helps you build clean, maintainable web apps. Many companies use Svelte or similar frameworks, and reusable behaviors save time and reduce bugs.
Progress0 / 4 steps
1
Create the Svelte action function
Write a Svelte action function called hoverHighlight that accepts a DOM element parameter and adds event listeners for mouseenter and mouseleave events. On mouseenter, set the element's background color to lightblue. On mouseleave, reset the background color to '' (empty string).
Svelte
Hint

Remember, a Svelte action is a function that receives a DOM element and can add event listeners. Return an object with a destroy method to clean up.

2
Set up the HTML elements to use the action
In the Svelte component, create two <div> elements with the texts Box 1 and Box 2. Import the hoverHighlight action and apply it to both <div> elements using the use:hoverHighlight directive.
Svelte
Hint

Use the use: directive to apply the action to elements.

3
Add a configuration option to the action
Modify the hoverHighlight action to accept a second parameter color that sets the highlight color. Use color = 'lightblue' as the default. Change the background color to the given color on mouse enter.
Svelte
Hint

Actions can accept a second parameter for options. Use it to set the highlight color.

4
Use the action with different colors on elements
Apply the hoverHighlight action to the first <div> with the default color. Apply it to the second <div> with the color 'lightgreen' by passing it as the second argument in the use:hoverHighlight directive.
Svelte
Hint

Pass the color as a parameter in curly braces inside the use: directive.