1

I'm using daisyui in svelte, and I don't know how to use the modal programmatically without <input> tag or <a> tag, is it possible to do? I want to be able to control the open/close of the modal through javascript. What's the most elegant way to do it?

The modal component is here.

Found this solution on the web, but isn't it kind of complicated for such a simple functionality?

Also tried to use the official example without <input> or <a>, replaced with {#if opened}, but failed to open the modal

H.B.
  • 166,899
  • 29
  • 327
  • 400
Zed Wong
  • 179
  • 7
  • 1
    Please include all relevant code inside the question itself (do not just link to it). – H.B. Nov 30 '22 at 09:54

1 Answers1

3

By default the component uses a checkbox state to open/close the modal. This makes it possible to add this interactivity without any JS at all. The documentation however states that there also is the class modal-open:

Add/remove this class to open/close the modal using JS

So that could be used with a local flag via class:modal-open={opened}.

H.B.
  • 166,899
  • 29
  • 327
  • 400
  • If I want to close the modal by clicking outside, what should I do? I want to avoid using – Zed Wong Nov 30 '22 at 12:10
  • 1
    You can use [``](https://svelte.dev/docs#template-syntax-svelte-window) to add a top level `click` event listener, then you just need to check if the event `target` is inside or outside the modal (you can bind the modal element to a variable using `bind:this`). – H.B. Nov 30 '22 at 13:00
  • 2
    Actually, the modal provides its own backdrop on which a listener can be added ([Example](https://svelte.dev/repl/a9e64888b96c473eb16dac894700dc18?version=3.53.1)). You would also want to add keyboard events for pressing escape. – H.B. Nov 30 '22 at 13:19