Search code examples
javascriptsveltesapper

How to nest a clickable checkbox in a container that is a link in svelte


I have a card component which should forward the user to another page when it is clicked. It contains a checkbox, which triggers some action. I want to forward the user when he clicks on the card, but not when he clicks on the checkbox.

I have tried around with self and stopPropagation on the card element, but it did not work. Is there a way to add this to the input element? Here is the code for some reference:

// Card Component
<div class="card" {style} on:click={() => goto(`${$page.path}/${app.name}`)}>
//...some code

  <Checkbox label="Compare Services" bind:checked={compare} />
</div>

// Checkbox Component
<label on:keypress={handleEnter} tabindex="1" class="checkbox-holder" {style}>
  <input type="checkbox" bind:checked />
  <div class="cool-checkbox">
    <div class="checkbox-square" class:checkbox-square-active={checked}>
      <i class={`fal fa-${checked ? 'check' : 'minus'}`} />
    </div>
    <span>{label}</span>
  </div>
</label>

Solution

  • Here is a working example:
    https://svelte.dev/repl/627262b5eadf4774845ec6f3818cd4b1?version=3.24.1

    I think you had it right, maybe you had some typo or something. You just need to add "|self" to onclick-statement in the Card-component

    on:click|self={()=>console.log("div clicked")}