Sub topic 3
Opening and closing a dialog from JavaScript
The dialog element does nothing until something opens it. This chapter covers the three methods that change a dialog's state, the open property that reports it, and the errors you get when you call a method in the wrong state.
Prerequisites
This chapter assumes you can:
- Write basic HTML, including
buttonandformelements. - Select elements with
document.getElementByIdorquerySelector. - Attach event listeners with
addEventListener.
It also assumes you know the difference between modal and non-modal dialogs from the previous chapter. Here the focus is on the API calls.
The three methods
Every HTMLDialogElement has three methods that change its state.
| Method | Effect | Typical use |
|---|---|---|
| `showModal()` | Opens the dialog as a modal. The browser puts it in the top layer, makes the rest of the page inert, and draws a `::backdrop`. | Confirmations, forms, anything that needs an answer before the user continues |
| `show()` | Opens the dialog as a non-modal. The page stays interactive and there is no backdrop. | Persistent panels, inline notices |
| `close(returnValue)` | Closes the dialog. The optional string becomes the dialog's `returnValue`. | Any close, from a button or from your own logic |
Two details apply to all three.
- The dialog must be connected to the document. Calling
showModal()on an element that was created but never appended throws anInvalidStateError. - The methods return
undefined. To react to the result, listen for events. Thecloseevent is covered in a later chapter.
The open property
A dialog is open when it has the open attribute. The open property reflects that attribute as a boolean.
const dlg = document.getElementById('dlg');
console.log(dlg.open); // false
dlg.showModal();
console.log(dlg.open); // true
dlg.close();
console.log(dlg.open); // falseThe attribute alone does not say how the dialog was opened. Both show() and showModal() set open. The browser also keeps an internal modal flag, which you cannot read directly. You can detect a modal dialog with the :modal pseudo-class. In script, dlg.matches(':modal') returns true only when the dialog was opened with showModal().
The diagram shows the three states and the calls that move between them.
A complete example
This page has two buttons that open the same dialog in different modes. The dialog has two buttons that close it. A close listener reports what happened.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Dialog API demo</title>
</head>
<body>
<button id="open-modal">Open as modal</button>
<button id="open-plain">Open as non-modal</button>
<p id="status">Status: closed</p>
<dialog id="dlg" aria-labelledby="dlg-title">
<h2 id="dlg-title">Notice</h2>
<p>Pick a way to close this dialog.</p>
<button id="close-plain">Close</button>
<button id="close-value">Close with a value</button>
</dialog>
<script>
const dlg = document.getElementById('dlg');
const status = document.getElementById('status');
function openDialog(modal) {
if (dlg.open) return; // guard against InvalidStateError
dlg.returnValue = ''; // clear the value from the previous session
if (modal) {
dlg.showModal();
} else {
dlg.show();
}
status.textContent = 'Status: open (' + (modal ? 'modal' : 'non-modal') + ')';
}
document.getElementById('open-modal')
.addEventListener('click', () => openDialog(true));
document.getElementById('open-plain')
.addEventListener('click', () => openDialog(false));
document.getElementById('close-plain')
.addEventListener('click', () => dlg.close());
document.getElementById('close-value')
.addEventListener('click', () => dlg.close('confirmed'));
dlg.addEventListener('close', () => {
status.textContent = 'Status: closed, returnValue = "' + dlg.returnValue + '"';
});
</script>
</body>
</html>Try it in both modes. When the dialog is modal, the two opener buttons cannot be clicked, because the page behind it is inert. When it is non-modal, you can click them. The if (dlg.open) return; guard then matters, because showModal() would throw on a dialog that show() already opened.
Calling a method in the wrong state
The rules differ by method, and they have changed slightly across spec revisions, so treat the guard as the portable approach.
| Call | Dialog state | Result |
|---|---|---|
| `show()` | Closed | Opens non-modal |
| `show()` | Already open non-modal | Does nothing |
| `show()` | Open as modal | Throws `InvalidStateError` |
| `showModal()` | Closed | Opens as modal |
| `showModal()` | Open non-modal | Throws `InvalidStateError` |
| `showModal()` | Already open as modal | Does nothing in current browsers. Older browsers throw. |
| `close()` | Closed | Does nothing |
An uncaught InvalidStateError stops your handler, so the dialog stays in whatever state it was in. This is common when two code paths can open the same dialog, for example a button and a keyboard shortcut. Funnel them through one function that checks open.
function ensureModal(dialog) {
if (dialog.open && !dialog.matches(':modal')) {
dialog.close(); // switch from non-modal to modal
}
if (!dialog.open) {
dialog.showModal();
}
}Closing and reopening is the supported way to change modes. There is no method that converts an open dialog in place.
Setting the open attribute directly
You can write <dialog open> in markup, or call dlg.setAttribute('open', ''), or set dlg.open = true. All of these show the dialog, and all of them produce a non-modal dialog. That is the same result as show(), with two differences.
- No
showModal()setup runs, so there is no top layer, backdrop, or inert page. - Your code and the browser can disagree about state. Initial focus handling also differs from
show().
Use the methods. Setting open directly is only reasonable for a dialog that should be part of the page from the first render, such as a static notice. Never use open="false". Any value of the attribute, including the string false, counts as present.
Passing a value to close()
close() takes an optional string. When you pass one, the browser stores it in dialog.returnValue before it fires the close event.
dlg.close('saved');
console.log(dlg.returnValue); // 'saved'If you call close() with no argument, returnValue keeps its old value. This causes a common bug. The dialog opens, the user presses Escape, and your close handler reads a value left over from the last time the dialog was used. The example above avoids this by setting dlg.returnValue = '' before each open. An empty string then means "closed without a choice".
returnValue is always a string. For structured results, such as a form's fields, read the form data in your handler instead of squeezing it into the return value. The next chapters on close events and form method="dialog" build on this.
Asking the dialog to close: requestClose()
close() closes the dialog immediately. Pressing Escape takes a different route: the browser fires a cancelable cancel event first, and only closes the dialog if no handler calls preventDefault().
Newer browsers expose that same route to your code as dialog.requestClose(returnValue). It fires cancel, respects preventDefault(), and then closes. Use it when a close button should behave like Escape, for example when you want an "unsaved changes" guard to run in both cases.
if (typeof dlg.requestClose === 'function') {
dlg.requestClose('dismissed');
} else {
dlg.close('dismissed'); // fallback for older browsers
}The feature check matters. requestClose() was added to browsers later than showModal() and close(), so test for it before relying on it.
Wiring many dialogs with one listener
Once a page has more than a couple of dialogs, repeating getElementById and a listener for each button gets tedious. Event delegation lets one listener serve every dialog. The opener names its target in a data-opens attribute, and a closer carries its result in data-closes.
<button data-opens="settings">Settings</button>
<button data-opens="help">Help</button>
<dialog id="settings" aria-label="Settings">
<p>Settings go here.</p>
<button data-closes="done">Done</button>
</dialog>
<dialog id="help" aria-label="Help">
<p>Help text goes here.</p>
<button data-closes="">Close</button>
</dialog>
<script>
document.addEventListener('click', (event) => {
const opener = event.target.closest('[data-opens]');
if (opener) {
const target = document.getElementById(opener.dataset.opens);
if (target && !target.open) target.showModal();
return;
}
const closer = event.target.closest('[data-closes]');
if (closer) {
closer.closest('dialog')?.close(closer.dataset.closes);
}
});
</script>The closer finds its own dialog with closest('dialog'). The button therefore works wherever you place it, and adding a third dialog needs only markup.
Errors to watch for
| Symptom | Likely cause | Fix |
|---|---|---|
| `InvalidStateError` when opening | The dialog is already open in the other mode, or is not in the document | Check `dlg.open` first. Append the element before calling the method. |
| Dialog appears but the page is still clickable | It was opened with `show()` or the `open` attribute | Call `showModal()` |
| Dialog does not appear at all | `display` was overridden in CSS, for example `dialog { display: flex; }` | Apply `display` only to `dialog[open]` |
| `returnValue` holds an old value | `close()` was called without an argument, or Escape was used | Reset `returnValue` to `''` before opening |
| `showModal` is not a function | The variable holds a different element, such as a `div` | Check the selector and the element's tag |
The CSS entry catches many people. The browser hides a closed dialog with the rule dialog:not([open]) { display: none; }. A plain dialog { display: flex; } in your stylesheet beats that rule, so the dialog shows even when it is closed.
Exercise
A page opens a dialog with dlg.show(). A keyboard shortcut handler then calls dlg.showModal() on the same dialog while it is open, and the console reports an InvalidStateError. Write the smallest change to the shortcut handler that makes it switch the dialog to modal mode without an error.
Show answer
Close the dialog first, then reopen it as a modal. For example: if (dlg.open && !dlg.matches(':modal')) dlg.close(); if (!dlg.open) dlg.showModal();. A dialog cannot be converted in place. The check for :modal also avoids closing a dialog that is already modal.
Exercise
Your close handler logs dlg.returnValue. The first time the user clicks "Save", it logs save. The second time, the user presses Escape and it logs save again, although nothing was saved. Why, and how do you fix it?
Show answer
Escape closes the dialog without setting a new returnValue, so the value from the previous session is still there. Reset it with dlg.returnValue = '' just before calling showModal(), and treat an empty string as "closed without a choice".