Effortless Dialog Closure: The `command="close"` Attribute

Web Development

Discover a straightforward method to implement dialog close buttons within HTML `<dialog>` headers by leveraging `command="close"`, offering a seamless, no-JavaScript solution for UI management.

Beyond using formmethod="dialog", HTML <dialog> elements can also be closed effortlessly with a dedicated button in the header utilizing the command="close" attribute. This provides an ideal solution for closing dialogs without requiring a <form>.

Consider the following example:

<dialog id="example-dialog" aria-labelledby="dialog-title" aria-describedby="dialog-desc">
  <header>
    <hgroup>
      <h2 id="dialog-title">Refund payment</h2>
      <p id="dialog-desc">
        Are you sure you want to refund this payment?
        The funds will be returned to the customer's account.
      </p>
    </hgroup>
    <button
      type="button"
      commandfor="example-dialog"
      command="close"
      aria-label="Close dialog"
    >&times;</button>
  </header>
</dialog>

In this implementation, the commandfor attribute links the button to the specific dialog's id (example-dialog), while command="close" instructs the browser to close the dialog upon interaction, entirely eliminating the need for JavaScript.

A demonstration of this functionality is available here: Dialog close button demo