Module 15: Modern Interactive HTML
The dialog Element
Create modal and non-modal dialogs using the browser’s native dialog behavior.
The dialog element represents a dialog box. JavaScript can open it as a modal dialog with showModal() or as a non-modal dialog with show().
<button type="button" id="open-dialog">View details</button>
<dialog id="details-dialog">
<h2>Order details</h2>
<p>Your order is ready for review.</p>
<form method="dialog">
<button type="submit">Close</button>
</form>
</dialog>
<script>
const dialog = document.querySelector("#details-dialog");
document.querySelector("#open-dialog").addEventListener("click", () => {
dialog.showModal();
});
</script>
A modal dialog places the rest of the document into an inert state and provides browser-managed modal behavior. The method="dialog" form can close the dialog without sending a request.
Include a heading and meaningful content. Decide where focus should go when the dialog opens and where it should return when it closes. The browser handles important parts of modal behavior, but the surrounding interface still needs testing.
Do not use a dialog for every small message. A non-modal status update may be better as inline feedback or a live region. Use a modal when the visitor needs to address the dialog before continuing with the page.