Sub topic 1
What the `dialog` Element Is
Prerequisites
You should know basic HTML structure, CSS selectors, and JavaScript DOM event listeners. This chapter assumes you can select an element and attach a click handler.
The `dialog` Element
The HTML dialog element represents a temporary window for a task, message, or choice. It can contain normal HTML, including headings, text, buttons, and forms.
A dialog is closed by default. JavaScript opens it by setting its open state through the dialog API. You usually should not manipulate the open attribute directly because the API also manages modal behavior and focus.
Modal versus Non-Modal: `show()` and `showModal()`
The show() method opens a non-modal dialog. The user can still interact with the rest of the page.
The showModal() method opens a modal dialog. The browser places it in the top layer, displays a backdrop, and makes the rest of the page inert. Inert content cannot receive normal pointer or keyboard interaction.
Use a modal dialog when the user must finish or dismiss a focused task before continuing. Use a non-modal dialog for temporary information that does not interrupt the page.
> callout note > A dialog opened with showModal() must be closed with close() or an equivalent user action. Calling showModal() again while the dialog is already open causes an error.
Opening and Closing from JavaScript
Call showModal() or show() on the dialog element. Call close() to remove it from view. The optional argument to close() becomes the dialog's returnValue, which later chapters use to report a result.
<!doctype html>
<button id="open">Open settings</button>
<dialog id="settings">
<h2>Settings</h2>
<p>Change your preferences here.</p>
<button id="close">Done</button>
</dialog>
<script>
const dialog = document.querySelector("#settings");
document.querySelector("#open").addEventListener("click", () => {
dialog.showModal();
});
document.querySelector("#close").addEventListener("click", () => {
dialog.close("done");
});
</script>Exercise
Which method should you use when the rest of the page must wait?
Show answer
Use showModal(). It opens the dialog modally and makes the page behind it inert.