tezvyn:

Handling Basic DOM Events in Svelte

AI-drafted, machine-checkedSource: svelte.devintermediate
Handling Basic DOM Events in Svelte

Svelte handles DOM events with `on:eventname` syntax in your markup, linking elements to functions in your script. This is for user interactions within a component, not for parent-child communication. The footgun is confusing this with custom component events.

WHY IT EXISTS: Web applications must respond to user actions like clicks, mouse movements, and keyboard input. Svelte integrates event handling directly into its component structure, providing a declarative and readable way to make UIs interactive without manually managing event listeners.

THE MENTAL MODEL: Think of it as adding an event listener directly onto your HTML element. Instead of finding the element in the DOM and calling element.addEventListener('click', ...) in your script, you simply write on:click={...} on the element itself. The Svelte compiler handles the boilerplate of wiring it up efficiently.

HOW IT WORKS: In a Svelte component, you define a function inside the <script> tag. In your template's HTML, you add an on: directive to an element, followed by the name of a standard DOM event, like on:click or on:mouseover. You then assign your function to this directive. When the user performs the action, Svelte executes your function. The onclick={greet} syntax seen in some examples is a familiar shorthand that is equivalent to on:click={greet}.

WHEN TO USE IT: Use on: directives for any standard browser DOM events that happen within a single component's template. This is the primary method for capturing user input like button clicks, form submissions, or mouse movements to trigger logic in your component's script.

WHEN NOT TO USE IT: This mechanism is not for communication between components. If a child component needs to send a notification or data up to its parent, direct DOM event handling is the wrong tool. That scenario requires Svelte's custom event dispatcher, which is a separate feature for component composition.

ONE CANONICAL EXAMPLE: A simple button that triggers an alert when clicked. Inside the <script> tag, you define a function: function greet() { alert('Welcome to Svelte!'); }. In the template, you create the button and attach the handler: <button on:click={greet}>click me</button>. Clicking this button will run the greet function.

Read the original → svelte.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.