HTML Tutorial · HTML5 Features · Lesson 23 of 34
HTML Dialog and Popover
Build accessible modal dialogs with <dialog> and lightweight popups with the popover attribute, without a library.
The dialog element
<dialog> is a native dialog box. Opened with showModal(), it becomes modal: the rest of the page is inert, focus moves into the dialog, the Esc key closes it and a ::backdrop covers the page.
<button id="open">Delete project</button>
<p id="result"></p>
<dialog id="confirm" aria-labelledby="title">
<form method="dialog">
<h2 id="title">Delete this project?</h2>
<p>This can't be undone.</p>
<button value="cancel">Cancel</button>
<button value="delete">Delete</button>
</form>
</dialog>
<style>dialog::backdrop { background: rgb(0 0 0 / 0.4); }</style>
<script>
const dialog = document.getElementById("confirm");
document.getElementById("open").addEventListener("click", () => dialog.showModal());
// On a real page, method="dialog" closes the dialog by itself. This preview blocks form
// submission, so the buttons close it from script with the same result value.
dialog.querySelectorAll("button").forEach((b) => b.addEventListener("click", (e) => { e.preventDefault(); dialog.close(b.value); }));
dialog.addEventListener("close", () => {
document.getElementById("result").textContent = "You chose: " + dialog.returnValue;
});
</script>
- A
<form method="dialog">inside closes the dialog when submitted, and the button'svaluebecomesdialog.returnValue. show()opens a non-modal dialog.- Listen for the
closeevent to react to the result.
The popover attribute
For menus, tooltips and teaching tips, the popover API needs no JavaScript: give an element popover and an id, and point a button at it with popovertarget. Popovers appear on top of everything, close when you click outside or press Esc, and only one "auto" popover is open at a time.
<button popovertarget="help">What is a CVC?</button>
<div id="help" popover>
<p>The CVC is the 3-digit code on the back of your card.</p>
<button popovertarget="help" popovertargetaction="hide">Got it</button>
</div>
<style>[popover] { padding: 1rem; border-radius: 8px; max-width: 16rem; }</style>
Dialog or popover?
| Use | Element |
|---|---|
| The user must respond before continuing (confirm, form) | <dialog> with showModal() |
| Extra information or a menu that can be dismissed | popover |
Test yourself
What happens when a <form method="dialog"> inside a dialog is submitted?
The page reloadsThe dialog closes and the submitting button's value becomes dialog.returnValueThe form is sent to the serverNothing until you call close()
Show answer
Answer: The dialog closes and the submitting button's value becomes dialog.returnValue
method="dialog" closes the dialog instead of sending a request.