0
0
Svelteframework~5 mins

Event modifiers (preventDefault, stopPropagation) in Svelte

Choose your learning style9 modes available
Introduction

Event modifiers help control how events behave in your app. They make it easy to stop default actions or stop events from spreading without extra code.

When you want to stop a form from submitting and refreshing the page.
When clicking a button inside a link should not follow the link.
When you want to prevent a parent element from reacting to a child's click.
When you want to keep your event handlers clean and simple.
Syntax
Svelte
<button on:click|preventDefault|stopPropagation={handler}>Click me</button>
Use preventDefault to stop the browser's default action for the event.
Use stopPropagation to stop the event from bubbling up to parent elements.
Examples
This stops the form from refreshing the page when submitted.
Svelte
<form on:submit|preventDefault={submitHandler}>
  <button type="submit">Submit</button>
</form>
The button click won't trigger the parent div's click handler.
Svelte
<div on:click={parentClick}>
  <button on:click|stopPropagation={childClick}>Click me</button>
</div>
Clicking the link won't navigate away because the default action is prevented.
Svelte
<a href="https://example.com" on:click|preventDefault={linkClick}>Link</a>
Sample Program

Clicking the button updates the message to 'Button clicked!' without triggering the parent div's click. The preventDefault here doesn't affect the button but shows how to chain modifiers.

Svelte
<script>
  let message = '';
  function handleClick() {
    message = 'Button clicked!';
  }
  function handleParentClick() {
    message = 'Parent clicked!';
  }
</script>

<div on:click={handleParentClick} style="padding: 1rem; border: 1px solid #ccc;">
  <button on:click|preventDefault|stopPropagation={handleClick}>
    Click me
  </button>
  <p>{message}</p>
</div>
OutputSuccess
Important Notes

Event modifiers make your code cleaner by avoiding manual calls to event.preventDefault() or event.stopPropagation().

You can chain multiple modifiers separated by |.

Use them thoughtfully to avoid unexpected behavior in nested elements.

Summary

Event modifiers control event behavior simply.

preventDefault stops default browser actions.

stopPropagation stops events from bubbling up.