Toni
Toni

Reputation: 1852

How to close DaisyUI drawer menu with just one click?

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

Upvotes: 4

Views: 9233

Answers (3)

G3N
G3N

Reputation: 321

Bind a variable to the input's checked

And toggle through the button or a tag with onclick

let drawerState = $state(false)

<input id="navbar-drawer" type="checkbox" class="drawer-toggle" bind:checked={drawerState} />

<NavbarItem {name} {href} onclick={() => (drawerState = false)} />

Upvotes: 0

Miguel
Miguel

Reputation: 111

Just add this to your <a> tag

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

Upvotes: 11

alexvdvalk
alexvdvalk

Reputation: 1234

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;
}

Upvotes: 0

Related Questions