📖 Scenario: You are building a simple interactive web page where a button changes color when clicked. You want to use a Svelte action to handle the click event and dispatch a custom event to notify the parent component.
🎯 Goal: Create a Svelte action that changes the button's background color on click and dispatches a custom event called colorChange. Then use this action in a button element and listen for the colorChange event to update a message.
📋 What You'll Learn
Create a Svelte action function named colorChanger that changes the element's background color to lightblue when clicked
Inside the action, dispatch a custom event named colorChange when the color changes
Use the colorChanger action on a <button> element
Listen for the colorChange event on the button and update a message variable to 'Button color changed!'
💡 Why This Matters
🌍 Real World
Custom actions with event dispatching let you add reusable interactive behaviors to elements in Svelte apps, like buttons, inputs, or custom widgets.
💼 Career
Understanding actions and event dispatching is important for building modular, maintainable UI components in modern web development with Svelte.
Progress0 / 4 steps
1
Create the Svelte action function
Create a Svelte action function called colorChanger that takes a parameter node and returns an object with a destroy method. Inside the function, add a click event listener to node that changes its background color to lightblue.
Svelte
Hint
Remember to add and remove the event listener inside the action function.
2
Add event dispatching inside the action
Modify the handleClick function inside the colorChanger action to dispatch a custom event named colorChange after changing the background color. Use node.dispatchEvent(new CustomEvent('colorChange')) to dispatch the event.
Svelte
Hint
Use node.dispatchEvent(new CustomEvent('colorChange')) inside the click handler to dispatch the event.
3
Use the action on a button and listen for the event
In the Svelte component, import the colorChanger action. Create a variable message initialized to an empty string. Add a <button> element that uses the use:colorChanger directive. Add an event listener for on:colorChange on the button that sets message to 'Button color changed!'. Below the button, display the message variable inside a <p> tag.
Svelte
Hint
Use the use: directive to apply the action and on: to listen for the event.
4
Complete the Svelte component with proper imports and usage
Ensure the Svelte component imports colorChanger from the correct file path. Confirm the button uses use:colorChanger and listens for on:colorChange. The component should display the message below the button. The code should be ready to run in a Svelte environment.
Svelte
Hint
Make sure the import path matches your file structure and the component syntax is correct.
Practice
(1/5)
1. What is the main purpose of an action in Svelte?
easy
A. To create new components
B. To add reusable behavior to HTML elements
C. To style elements with CSS
D. To manage global state
Solution
Step 1: Understand what actions do
Actions in Svelte are functions that add behavior to elements, like event listeners or animations.
Step 2: Compare options
Only To add reusable behavior to HTML elements correctly describes adding reusable behavior to elements, while others describe unrelated tasks.
Final Answer:
To add reusable behavior to HTML elements -> Option B
Quick Check:
Actions = reusable element behavior [OK]
Hint: Actions add behavior to elements, not create components [OK]
Common Mistakes:
Confusing actions with components
Thinking actions manage styles
Assuming actions handle global state
2. Which of the following is the correct way to dispatch a custom event named notify from a Svelte action?
easy
A. new Event('notify').dispatch(node)
B. dispatch('notify')
C. dispatchEvent('notify')
D. node.dispatchEvent(new CustomEvent('notify'))
Solution
Step 1: Recall how to dispatch events in Svelte actions
Custom events are dispatched using node.dispatchEvent(new CustomEvent('eventName')).
Step 2: Check each option
node.dispatchEvent(new CustomEvent('notify')) matches the correct syntax. Others are either missing new CustomEvent or use invalid syntax.
Final Answer:
node.dispatchEvent(new CustomEvent('notify')) -> Option D
The code calls CustomEvent('myEvent') without the new keyword, which is required to create an event instance.
Step 2: Verify other parts
Event listener is correctly added and removed; destroy method exists; event names can be uppercase.
Final Answer:
Missing 'new' keyword before CustomEvent -> Option C
Quick Check:
CustomEvent requires 'new' keyword [OK]
Hint: Always use 'new CustomEvent' to create events [OK]
Common Mistakes:
Forgetting 'new' before CustomEvent
Removing event listener incorrectly
Assuming event names must be lowercase
5. You want to create a Svelte action that dispatches a custom event resize whenever the window is resized. Which of the following is the best way to implement this action?
hard
A. Add a window 'resize' listener inside the action, dispatch 'resize' event from the node, and clean up in destroy
B. Add a 'resize' listener to the node element directly and dispatch event from node
C. Dispatch 'resize' event once when the action is initialized
D. Use a setInterval to check window size and dispatch event repeatedly
Solution
Step 1: Understand event source and dispatch
Window resize events come from the window object, so the listener must be added to window, not the node.
Step 2: Implement dispatch and cleanup
The action should dispatch a custom 'resize' event from the node when window resizes, and remove the listener in destroy to avoid leaks.
Final Answer:
Add a window 'resize' listener inside the action, dispatch 'resize' event from the node, and clean up in destroy -> Option A
Quick Check:
Listen on window, dispatch from node, cleanup in destroy [OK]
Hint: Listen on window, dispatch from node, cleanup in destroy [OK]
Common Mistakes:
Adding listener to node instead of window
Not cleaning up event listener
Dispatching event only once
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.