<dialog>

Draft

Definition

The <dialog> HTML element is used to create a modal or popup dialog box within a web page. It provides a way to present interactive content or messages to the user that requires their attention or input before continuing with other actions on the page.

Here’s an example of how to use the <dialog> element:

HTML

Confirmation

Are you sure you want to delete this item?

Code
<dialog id="myDialog">
  <h2 class="font-bold">Confirmation</h2>
  <p>Are you sure you want to delete this item?</p>
  <button class="px-4 py-2 mt-4 border border-black" onclick="document.getElementById('myDialog').close()">Cancel</button>
  <button class="px-4 py-2 mt-4 text-white bg-black border" onclick="document.getElementById('myDialog').close()">Confirm</button>
</dialog>

<button class="px-4 py-2 text-white bg-black border" onclick="document.getElementById('myDialog').showModal()">
  Open Dialog
</button>

In this example, the <dialog> element represents a dialog box with a title, a message, and two buttons for canceling or confirming an action. The id attribute is used to uniquely identify the dialog box.

To open the dialog box, a JavaScript event handler is added to a button using the onclick attribute. When the button is clicked, the showModal() method is called on the dialog element, displaying the dialog as a modal overlay on top of the page. The user can interact with the dialog, and the buttons can trigger corresponding actions or close the dialog.

The <dialog> element provides a convenient way to create custom modal dialogs without the need for external libraries or frameworks. It supports various methods and events, such as showModal(), close(), or cancel, allowing you to control the dialog’s behavior programmatically.

It’s important to note that browser support for the <dialog> element may vary, and you may need to use JavaScript-based alternatives or polyfills for wider compatibility.