🎪 Svelte Event Handling: Teaching Your App to Listen!
The Story: Your App is Like a Friendly Pet
Imagine your app is like a smart puppy 🐕. When you say “Sit!”, the puppy sits. When you clap, it comes running. Your puppy listens for your commands and reacts to them.
In Svelte, events are those commands. When a user clicks a button, types in a box, or moves their finger — your app listens and responds!
🎯 What We’ll Learn
graph LR A[Event Handling] --> B[Event Attributes] A --> C[Inline Handlers] A --> D[Event Modifiers] A --> E[Event Forwarding] A --> F[Callback Props]
1. Event Attributes: Giving Your App Ears 👂
What’s an Event Attribute?
Think of it like putting a doorbell on your button. When someone presses it, something happens!
In Svelte, we use on: followed by the event name.
Simple Example
<script>
function sayHello() {
alert('Hello there!')
}
</script>
<button on:click={sayHello}>
Click Me!
</button>
What’s happening?
on:click= “Listen for a click”{sayHello}= “When clicked, run this function”
Common Events You Can Listen For
| Event | When It Happens |
|---|---|
on:click |
User clicks/taps |
on:input |
User types something |
on:submit |
Form is submitted |
on:keydown |
Key is pressed |
on:mouseover |
Mouse hovers over |
Real Life Example
<script>
let count = 0
function addOne() {
count = count + 1
}
</script>
<p>Count: {count}</p>
<button on:click={addOne}>
Add One
</button>
Every click = count goes up by 1! 🎉
2. Inline Event Handlers: Quick & Easy! ⚡
What’s an Inline Handler?
Instead of writing a separate function, you write the code right there in the HTML. Like leaving a sticky note on the doorbell that says what to do!
Simple Example
<script>
let name = 'Friend'
</script>
<button on:click={() => name = 'Buddy'}>
Change Name
</button>
<p>Hello, {name}!</p>
The magic: () => name = 'Buddy' is a tiny function written right in place!
When to Use Inline Handlers
✅ Good for: Simple, one-line actions
<button on:click={() => count++}>
+1
</button>
❌ Not great for: Complex logic with many steps
Getting Event Information
Sometimes you need details about the event. Use the event parameter:
<input
on:input={(event) => {
console.log(event.target.value)
}}
placeholder="Type here..."
/>
event.target.value = what the user typed!
3. Event Modifiers: Special Instructions! 🎛️
What Are Modifiers?
Modifiers are like extra rules for your events. They change how the event behaves.
Add them with a | pipe character: on:click|modifier
The Modifier Menu
| Modifier | What It Does |
|---|---|
preventDefault |
Stops default behavior |
stopPropagation |
Stops event bubbling up |
once |
Only triggers ONE time |
self |
Only if clicked directly |
capture |
Listens during capture phase |
passive |
Improves scroll performance |
Example: Prevent Default
When you submit a form, browsers normally refresh the page. Stop that!
<form on:submit|preventDefault={handleSubmit}>
<input type="text" />
<button>Send</button>
</form>
No page refresh! 🎉
Example: Once (One Time Only)
<button on:click|once={celebrate}>
Click for Surprise!
</button>
The surprise only happens once. Click again? Nothing!
Combining Modifiers
Stack them up like building blocks:
<button on:click|once|preventDefault={doSomething}>
Special Button
</button>
4. Event Forwarding: Passing Messages Up! 📤
The Problem
Imagine this: You have a fancy button component. Someone uses your component and wants to know when it’s clicked. How do they listen?
The Solution: Forward the Event!
Child Component (FancyButton.svelte):
<button on:click>
<slot />
</button>
See that on:click with nothing after it? That means “pass this event to whoever uses me!”
Parent Component:
<script>
import FancyButton from './FancyButton.svelte'
function handleClick() {
console.log('Button was clicked!')
}
</script>
<FancyButton on:click={handleClick}>
Click Me!
</FancyButton>
The click “bubbles up” from child to parent! 🫧
Forwarding Multiple Events
<!-- FancyInput.svelte -->
<input
on:input
on:focus
on:blur
/>
Now parent can listen to all three events!
5. Callback Props: Your Own Custom Events! 🎁
What’s a Callback Prop?
Instead of forwarding browser events, you create your own custom events!
It’s like inventing a new doorbell sound that means something special.
Simple Example
Child Component (Counter.svelte):
<script>
export let onCountChange
let count = 0
function increment() {
count++
if (onCountChange) {
onCountChange(count)
}
}
</script>
<button on:click={increment}>
Count: {count}
</button>
Parent Component:
<script>
import Counter from './Counter.svelte'
function handleCountChange(newCount) {
console.log('Count is now:', newCount)
}
</script>
<Counter onCountChange={handleCountChange} />
Why Use Callback Props?
- Custom data: Send any information you want
- Clear naming:
onSave,onDelete,onUserSelect - Full control: Decide exactly when to call them
Real World Example
<!-- TodoItem.svelte -->
<script>
export let todo
export let onDelete
export let onToggle
</script>
<div>
<input
type="checkbox"
checked={todo.done}
on:change={() => onToggle(todo.id)}
/>
<span>{todo.text}</span>
<button on:click={() => onDelete(todo.id)}>
🗑️
</button>
</div>
<!-- Parent -->
<script>
import TodoItem from './TodoItem.svelte'
let todos = [
{ id: 1, text: 'Learn Svelte', done: false }
]
function deleteTodo(id) {
todos = todos.filter(t => t.id !== id)
}
function toggleTodo(id) {
todos = todos.map(t =>
t.id === id ? {...t, done: !t.done} : t
)
}
</script>
{#each todos as todo}
<TodoItem
{todo}
onDelete={deleteTodo}
onToggle={toggleTodo}
/>
{/each}
🎯 Quick Summary
graph TD A[User Does Something] --> B{What Kind?} B --> C[Browser Event<br/>click, input, etc.] B --> D[Custom Action<br/>save, delete, etc.] C --> E[on:event] D --> F[Callback Props] E --> G[Add Modifiers?] G --> H[on:click|once] E --> I[Forward to Parent?] I --> J[on:click with no handler]
🏆 What You Learned!
| Concept | One-Line Summary |
|---|---|
| Event Attributes | on:click={handler} listens for events |
| Inline Handlers | on:click={() => ...} for quick actions |
| Event Modifiers | on:click|once adds special behavior |
| Event Forwarding | on:click alone passes event to parent |
| Callback Props | export let onSomething for custom events |
🎪 The Big Picture
Your Svelte app is always listening. Users click, type, scroll, and your app responds. You now know:
- How to listen (Event Attributes)
- Quick responses (Inline Handlers)
- Special rules (Modifiers)
- Passing messages (Forwarding)
- Custom signals (Callback Props)
You’re ready to make your apps interactive and alive! 🚀
Remember: Events are just your app paying attention. The more you listen, the better experience you create!
