Search code examples
javascriptonclicksvelte-3

clicking on child element, calls parents on:click function in svelte


when a child element is clicked the event attached to the parent gets triggered in svelte. I tried the same approach in simple CSS and HTML it worked perfectly whereas in svelte the parent action gets triggered. I have a REPL code below which simulates my scenario where clicking inside child prints "hi" in the console.

<script>
let name = 'world';
</script>
<div style="padding:50px; border:solid;height:200px; z-index:1" on:click={() => {console.log('hi')}}>
    <div style="border:solid;height:200px; z-index:999">
        <h1>Hello {name}!</h1>
    </div>
</div>

Solution

  • you have to use self modifier svelte event event-modifiers

    <div style="padding:50px; border:solid;height:200px; z-index:1" on:click|self={() => {console.log('hi')}}>...</div>