Discover how a tiny change in event handling can save you hours of debugging!
Why Inline event handlers in Svelte? - Purpose & Use Cases
Imagine building a webpage where every button needs to do something when clicked. You write separate JavaScript code to find each button and add event listeners manually.
This manual way is slow and confusing. You might forget to connect a button, or add the wrong event. It's hard to keep track of which code belongs to which button, especially as the page grows.
Inline event handlers let you write the event code right next to the button in your Svelte file. This keeps your code simple, clear, and easy to follow because the action is directly connected to the element.
const btn = document.querySelector('#myBtn'); btn.addEventListener('click', () => alert('Clicked!'));
<button on:click={() => alert('Clicked!')}>Click me</button>Inline event handlers make your code cleaner and faster to write, so you can build interactive apps without juggling separate scripts.
Think of a quiz app where each answer button immediately shows if you're right or wrong. Inline event handlers let you add that behavior right inside the button's code.
Manual event setup is slow and error-prone.
Inline handlers keep event code close to the element.
This makes your app easier to build and maintain.