Sub topic 2
Modal versus non-modal: show() and showModal()
This chapter assumes you can write basic HTML forms, select elements with CSS selectors, and attach event listeners in JavaScript. It also assumes you have seen a <dialog> element before. Here you will learn the two ways to open a dialog, what each one changes in the page, and how to choose between them.
The two ways to open a dialog
A <dialog> element is hidden by default. You make it visible in one of two ways, and the choice decides how the whole page behaves while the dialog is open.
dialog.show()opens a non-modal dialog. The rest of the page stays interactive.dialog.showModal()opens a modal dialog. The rest of the page becomes inert, which means it cannot be clicked, focused, or read by assistive technology until the dialog closes.
Both methods add the open attribute to the element. Both are closed with dialog.close(). The difference is in what the browser does around the dialog.
The following example uses show():
<dialog id="plain">
<p>This dialog is non-modal.</p>
<button onclick="this.closest('dialog').close()">Close</button>
</dialog>
<script>
const plain = document.getElementById('plain');
plain.show(); // non-modal: page stays interactive, no backdrop
// plain.showModal(); // modal: top layer, backdrop, rest of page inert
</script>Swap the commented line in and the behavior changes completely. With showModal() you get a dimmed backdrop, the page behind stops responding, and pressing Escape closes the dialog.
Comparing the two modes
| Behavior | `show()` (non-modal) | `showModal()` (modal) |
|---|---|---|
| Rest of the page | Stays interactive | Becomes inert |
| Placement | Normal stacking order, positioned in the document | Top layer, above all other content |
| `::backdrop` pseudo-element | Not rendered | Rendered |
| Escape key | Does nothing | Fires `cancel`, then closes |
| Initial focus | Moves to the first focusable element only if you ask with `autofocus` | Moves into the dialog automatically |
| Focus containment | None. Users can tab out | Focus stays within the dialog and the browser UI |
| Focus on close | Not restored automatically in all browsers | Returns to the element that had focus before opening |
The focus rows are the ones most often misremembered, so treat them as a rule of thumb. Browsers differ in small details for non-modal dialogs, and you should test the behavior you depend on.
The modal case: what changes
Calling showModal() does three things that you would otherwise build by hand.
- It promotes the dialog to the top layer. The top layer is a browser-managed stack that sits above the normal page, regardless of
z-indexor parentoverflowclipping. A modal dialog nested deep in your markup still draws over everything. - It makes everything outside the dialog inert. Inert content cannot receive clicks, focus, or text selection, and assistive technology skips it.
- It adds a
::backdroppseudo-element behind the dialog, which you can style.
Later chapters cover the top layer, focus, and backdrop styling in detail. For now the point is that you pay for none of this in JavaScript. One method call replaces a focus trap, an overlay div, and z-index management.
The non-modal case: what you give up and gain
A non-modal dialog behaves like a positioned box in the page flow. It does not block the user, and the user can keep working while it is visible.
Because it has no backdrop and no Escape handling, you take on more work:
- You decide how the user dismisses it. Provide a visible close button.
- You position it. A non-modal dialog without styling sits in normal flow with the default centered-looking margins of the user agent stylesheet, which may not be where you want it.
- You may need to manage stacking with
z-indexif other positioned elements overlap it.
In return, the dialog suits content that supports the page without interrupting it. Common examples are a floating help panel, a color picker beside a canvas, a cookie notice that does not block reading, or a chat widget.
Choosing between them
Ask one question: should the user be allowed to do anything else until this is answered?
- If the answer is no, use
showModal(). Confirmations, destructive-action warnings, forms that must be completed or cancelled, and login prompts fit here. - If the answer is yes, use
show(). Inspectors, side tools, and notifications fit here.
If you are unsure, the modal behavior is the safer default for anything that asks the user to make a decision. The built-in focus handling and Escape support are what keyboard and screen reader users expect from a modal.
Be careful not to use a modal for content that is merely informational. A modal that blocks the page for a message the user did not need to act on is an annoyance. For a passing message, a non-modal dialog or a different element may fit better.
Using the open attribute directly
You can also write <dialog open> in markup. This shows the dialog as non-modal, with the same behavior as show(). It does not produce a modal.
<dialog open>
<p>Visible on load, but not modal.</p>
</dialog>Do not toggle the open attribute from JavaScript to open a dialog you want to be modal. Setting the attribute never creates a top layer entry, a backdrop, or inertness. Always call a method:
const dlg = document.getElementById('dlg');
dlg.showModal(); // correct for a modal
// dlg.setAttribute('open', ''); // opens non-modally, and skips the modal setupThe reverse also matters. Closing by removing the attribute skips the close event and the return-value logic. Use close() unless you have a specific reason not to.
Checking state and avoiding errors
The open property tells you whether the dialog is currently showing. Use it to guard calls:
const dlg = document.getElementById('dlg');
function openModal() {
if (!dlg.open) {
dlg.showModal();
}
}The guard matters because the methods are strict about the current state.
- Calling
showModal()on a dialog that is already open as a modal does nothing in current browsers. Per the specification, calling it on a dialog already open as non-modal throws anInvalidStateError. - Calling
show()on a dialog that is already open does nothing, unless it is open as a modal. In that case it throwsInvalidStateError. - Calling
showModal()on a dialog that is not connected to the document also throwsInvalidStateError.
The practical rule is that you cannot switch a dialog between modes by calling the other method. Close it first, then reopen it:
function reopenAsModal(dialog) {
if (dialog.open) {
dialog.close();
}
dialog.showModal();
}Older browser versions treated the repeated-call cases differently, so write the open guard once and you avoid the differences.
Telling modal from non-modal at runtime
Sometimes you need to know which mode a dialog is in, for example to decide whether to attach a backdrop click handler. The :modal CSS pseudo-class matches a dialog opened with showModal() and does not match one opened with show(). The same check is available in JavaScript:
const isModal = dlg.matches(':modal');
console.log(isModal ? 'modal' : 'non-modal or closed');You can also use :modal in CSS to style only the modal case:
dialog:modal {
border: none;
box-shadow: 0 10px 40px rgb(0 0 0 / 0.3);
}
dialog:not(:modal) {
border: 1px solid #888;
}This is a clean way to give the two modes different looks without adding classes.
Common mistakes at this stage
- Using
setAttribute('open', '')or theopenattribute to open a modal. The dialog appears but the page stays interactive and there is no backdrop. UseshowModal(). - Expecting Escape to close a non-modal dialog. It does not. Add your own close button, or your own key handler.
- Calling
showModal()twice. Guard withdialog.open. - Trying to open the same dialog as modal while it is non-modal. Close it first.
- Forgetting that a modal dialog hides the page from screen readers. If something outside the dialog needs to be announced while it is open, such as a toast, it has to live inside the dialog or in the top layer as well.
A complete example with both modes
This page has one button for each mode. The modal one blocks the page, and the non-modal one does not. Try typing in the text field while each is open.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>show() versus showModal()</title>
<style>
dialog:modal::backdrop {
background: rgb(0 0 0 / 0.5);
}
dialog:not(:modal) {
position: fixed;
inset: auto 1rem 1rem auto;
margin: 0;
}
</style>
</head>
<body>
<input type="text" placeholder="Try typing here">
<button id="open-modal">Open modal</button>
<button id="open-plain">Open non-modal</button>
<dialog id="modal" aria-labelledby="modal-title">
<h2 id="modal-title">Modal</h2>
<p>The page behind is inert.</p>
<button class="close">Close</button>
</dialog>
<dialog id="plain" aria-labelledby="plain-title">
<h2 id="plain-title">Non-modal</h2>
<p>The page behind still works.</p>
<button class="close">Close</button>
</dialog>
<script>
const modal = document.getElementById('modal');
const plain = document.getElementById('plain');
document.getElementById('open-modal').addEventListener('click', () => {
if (!modal.open) modal.showModal();
});
document.getElementById('open-plain').addEventListener('click', () => {
if (!plain.open) plain.show();
});
document.querySelectorAll('dialog .close').forEach((button) => {
button.addEventListener('click', () => button.closest('dialog').close());
});
</script>
</body>
</html>Here is what to observe. With the modal open, the text field cannot be focused or clicked, the page is dimmed, and Escape closes the dialog. With the non-modal open, you can type in the field, there is no dimming, and Escape does nothing.
Exercise
A teammate writes dialog.setAttribute('open', '') to show a confirmation prompt, and then reports that users can still click the buttons behind it and that no dimmed backdrop appears. What is wrong, and how do you fix it?
Show answer
Setting the open attribute opens the dialog non-modally, which skips the top layer, the inert page, and the backdrop. Replace it with dialog.showModal(), and close it with dialog.close(). Guard the call with if (!dialog.open) so a repeated call does not cause an error.
Exercise
A dialog is currently open as non-modal. A button handler calls dialog.showModal() on it. What happens, and what should the handler do instead if you want a modal?
Show answer
The call throws an InvalidStateError, because a dialog cannot change modes while it is open. The handler should call dialog.close() first and then dialog.showModal().