Search code examples
onclickevent-handlingsveltemousedownevent-propagation

Event Propagation in Svelte


When interacting with a child component, the parent component's event triggers. Below is an example of my code:

<!-- Parent Component -->
<div class="parent" on:click={toggle}>
     {#if expand}
             <Child />
     {/if}
</div>

<!-- Child Component -->
<div class="child" on:mousedown|stopPropagation={execute}>
     text
</div>

I tried using stopPropagation and preventDefault in-line and in the function calls.


Solution

  • Those are different events, stopping one type will not stop the other, even if they both relate to the action of clicking. You would have to stop click on the child if you listen to click on the parent.

    Also, use buttons.

    If you only want to trigger the handler on clicks on that specific element, not its descendants, you can also use the self modifier, e.g.

    <button on:click|self={onClick}>