AHA demos
← All demos

Modal dialog

A form that lives in a native dialog. The form loads from the server when you open it. The server decides when it closes.

Hello, stranger.

What to look at

The dialog is the browser's own <dialog>. Alpine holds one boolean, open, and an x-effect calls showModal() or close() whenever it changes. Escape fires the dialog's close event, which sets open back to false. A click on the backdrop lands on the dialog element itself, so @click.self closes it too.

The button does two things at once: hx-get loads the form into the dialog body, and @click opens it.

Submitting the form posts to the server. If the name is bad, the server answers 422 with the form re-rendered and an error message. htmx 4 swaps error responses by default, so the form replaces itself.

If the name is good, the server returns the greeting as an oob swap and sets a response header: HX-Trigger: profile-saved. htmx turns that header into a DOM event. Alpine listens for it with @profile-saved.window and closes the dialog. The server decided the modal should close, without knowing anything about modals.

Source

Loading source…

Every file of this demo, as it runs. Or browse it on GitHub ↗