Datastar Dialog

As a hypermedia-first framework, you may think that all Datastar interactions should involve a server round trip.
However, there are times when you wouldn't want to use the server to manage the user state. A common scenario is a modal screen that you would like to present to the user after clicking a button.

Unlike HTMX, which often requires Alpine.js to manage client-side interactions, Datastar's built-in API allows you to control the client directly without an extra library.

In the example below, you can see how to control an HTML native dialog with just a few D* attributes.

Click the button to see it in action and check out the code below to learn how to do it.

example1

<div>
  <div data-signals-open="false" />
  <button class={"btn"} data-on-click="window.my_modal.showModal()">
    Click to open dialog
  </button>
  <dialog
    id="my_modal"
    className={"m-auto w-1/4 aspect-3/2 backdrop:blur-md backdrop:bg-slate-600/50 bg-slate-300"}
  >
    <div
      className={"h-full w-full bg-slate-800 p-5 m-auto"}
      data-on-click__outside__capture="window.my_modal.open ? window.my_modal.close() : null"
    >
      <button
        data-on-click="window.my_modal.close()"
        className="btn btn-sm btn-circle btn-ghost absolute right-2 top-2"
      >

      </button>
      <p>Dialog content</p>
      <p>
        To close press escape, click outside or click on the x button on the top
        left
      </p>
    </div>
  </dialog>
</div>;