2

I'm using the DaisyUI drawer component to render a menu on mobile. See here for a working example: https://daisyui.com/components/drawer

Now in the example there's a button which can be used to open and close the mobile menu.

The button triggers a checked status on following checkbox to show/hide the drawer:

<input id="my-drawer" type="checkbox" class="drawer-toggle">

My code:

let checked = 'checked';

function handleClick() {
    (checked == 'checked') ? checked = '': checked = 'checked';
}

On the input:

<input id="my-drawer-3" type="checkbox" class="drawer-toggle" bind:checked={checked}>

On the menu item:

<a on:click={handleClick} href='/test'>Test</a>

The problem is that I have to click two times to hide the drawer. The first click triggers a visual effect on the menu item. The second click closes the drawer. How can I achive the same result with just one click?

DEMO Link:
https://svelte.dev/repl/c06f018ac84f4b86b1d37f7576d25db1?version=3.29.7

ninsky
  • 1,772
  • 23
  • 31
  • Could you please provide a [REPL](https://svelte.dev/repl/hello-world?version=3.44.1)? – johannchopin Nov 12 '21 at 12:26
  • To start with: svelte checkbox binding return true or false. docs: https://svelte.dev/tutorial/checkbox-inputs – voscausa Nov 12 '21 at 12:52
  • Hmm difficult. On TailwindPlay I can't add svelte and and on REPL I can't add TailwindCSS with DaisyUI. Have to fiddle this out... – ninsky Nov 12 '21 at 12:57
  • @voscausa the binding from my code is working so far. I think I have to skip the visual effect somehow in order the checked state gets set immediately not requirering another click. – ninsky Nov 12 '21 at 13:03
  • You can import daisyUI/tailwind in the REPL in a `svelte:head` [like this](https://svelte.dev/repl/0a285ee88f474578833e8b1c9abe79bc?version=3.29.7)? – Corrl Nov 12 '21 at 14:22
  • @Corrl thanks for your link! Very helpful. I've added a demo link to the description text. – ninsky Nov 12 '21 at 22:47

2 Answers2

6

Just add this to your <a> tag

<a on:click={() => {document.getElementById('my-drawer-3').click()}} href='/test'>Test</a>
Miguel
  • 61
  • 1
  • 3
0

I'm not sure if this will help, but the variable 'checked' should be a boolean. Your logic could work because a '' string is falsy, but it would be best to rule that out.

let checked = false;
const handleClick = () =>{
  checked = !checked;
}

justintimeza
  • 1,064
  • 4
  • 8