Sub topic 2
What the Browser Does for You: Top Layer and Inert Content
Assume you know basic HTML forms, CSS selectors, and JavaScript event listeners.
Top Layer and Inert Content
When you call showModal(), the browser places the <dialog> in the top layer. The top layer is a browser-managed layer above normal page content. It does not depend on z-index.
The browser also makes the rest of the document inert. Inert content cannot receive clicks, keyboard focus, or most user interaction while the modal is open. This prevents users from accidentally working with the page behind the dialog.
> callout note > show() opens a non-modal dialog. It does not use the same blocking behavior: the page remains interactive and there is no modal backdrop.
Escape, `cancel`, and `close`
Pressing Escape on a modal dialog normally starts this sequence:
- The browser dispatches a cancelable
cancelevent. - If no listener prevents the event, the browser closes the dialog.
- The browser dispatches the
closeevent.
Use cancel when you need to approve or reject Escape-based dismissal. Use close when you need to react after any closing method, including close(), Escape, or a dialog form.
<dialog id="settings">
<h2>Settings</h2>
<button id="done">Done</button>
</dialog>
<script>
const dialog = document.querySelector("#settings");
dialog.addEventListener("cancel", (event) => {
console.log("Escape was pressed");
// event.preventDefault(); // Keep the dialog open.
});
dialog.addEventListener("close", () => {
console.log("Dialog closed:", dialog.returnValue);
});
document.querySelector("#done").addEventListener("click", () => {
dialog.close("done");
});
dialog.showModal();
</script>Returning Results with `form method="dialog"`
A form with method="dialog" closes its dialog instead of sending data to a server. The clicked submit button's value becomes dialog.returnValue.
<dialog id="confirm">
<form method="dialog">
<p>Delete this item?</p>
<button value="cancel" formnovalidate>Cancel</button>
<button value="delete">Delete</button>
</form>
</dialog>Read the result in the close handler. Use formnovalidate when a button should bypass required-field validation.
Where Focus Goes
When a modal opens, focus moves into the dialog. An element with autofocus receives focus first. Otherwise, the browser chooses a suitable focusable element.
When the dialog closes, focus normally returns to the element that opened it, if that element still exists and can receive focus. Avoid removing or disabling that element while the dialog is open.
Exercise
Which event should you prevent to stop Escape from closing a modal?
Show answer
Prevent the cancel event with event.preventDefault(). The close event happens after the dialog has already closed.