A Customized Confirmation UI

htmx supports the hx-confirm attribute to provide a simple mechanism for confirming a user action. This uses the default confirm() function in javascript which, while trusty, may not be consistent with your applications UX.

In this example we will see how to use sweetalert2 and the htmx:confirm event to implement a custom confirmation dialog.

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<button hx-get="/confirmed"
        _="on htmx:confirm(issueRequest)
             halt the event
             call Swal.fire({title: 'Confirm', text:'Do you want to continue?'})
             if result.isConfirmed issueRequest()">
  Click Me
</button>

We add some hyperscript to invoke Sweet Alert 2 on a click, asking for confirmation. If the user confirms the dialog, we trigger the request by invoking the issueRequest() function, which was destructured from the event detail object.

Note that we are taking advantage of the fact that hyperscript is async-transparent and automatically resolves the Promise returned by Swal.fire().

A VanillaJS implementation is left as an exercise for the reader. :)

Server Requests ↑ Show

🔗Demo