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

1

7

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>
Cliff answered 1/3, 2021 at 12:50 Comment(0)
M
10

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>
Manheim answered 1/3, 2021 at 12:55 Comment(1)
see also stopPropagationWillock

© 2022 - 2024 — McMap. All rights reserved.