Sub topic 3
Opening and closing a dialog from JavaScript
This chapter assumes you know basic HTML structure, CSS selectors, and how to select elements and add event listeners in JavaScript. It also assumes you know that a <dialog> element is hidden until it is opened.
The three methods
A <dialog> element has three methods that control whether it is shown.
| Method | What it does |
|---|---|
| `showModal()` | Opens the dialog as a modal. The rest of the page becomes inert. |
| `show()` | Opens the dialog as a non-modal. The page stays interactive. |
| `close(returnValue)` | Closes the dialog. The optional argument is stored in `dialog.returnValue`. |
All three work by changing the dialog's open attribute. You can read the matching dialog.open property to check the current state. Don't set the open attribute by hand to show a dialog. Doing so opens it as a non-modal, with no backdrop and no focus handling.
Opening a modal
Give the dialog an id, then call showModal() from a click handler.
<button id="open">Edit profile</button>
<dialog id="dlg" aria-labelledby="dlg-title">
<h2 id="dlg-title">Edit profile</h2>
<p>Changes are saved when you press Save.</p>
<button id="done">Done</button>
</dialog>
<script>
const dlg = document.getElementById('dlg');
document.getElementById('open').addEventListener('click', () => {
dlg.showModal();
});
document.getElementById('done').addEventListener('click', () => {
dlg.close('done');
});
dlg.addEventListener('close', () => {
console.log('closed with:', dlg.returnValue);
});
</script>Clicking the first button opens the dialog. Clicking Done calls close('done'). The browser then fires a close event, and the handler logs done.
Opening a non-modal
Use show() when the dialog should not block the page, such as a floating panel or a status message.
<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();
</script>A non-modal dialog has no backdrop, and the user can still click the rest of the page. Escape does not close it either. Your own code has to provide a way to close it, as the Close button does here.
The states of a dialog
The returnValue
close() accepts an optional string. The browser stores it in dialog.returnValue, so code that reads the close event can learn how the dialog ended.
const dlg = document.getElementById('dlg');
dlg.addEventListener('close', () => {
if (dlg.returnValue === 'save') {
console.log('User chose to save');
} else {
console.log('User dismissed the dialog');
}
});
// Elsewhere, for example in a Save button handler:
dlg.close('save');If you call close() with no argument, returnValue keeps its previous value. A dialog that has never been given a value has an empty string. If your code branches on returnValue, reset it before each open with dlg.returnValue = ''. Otherwise a later Escape press can look like the previous choice.
The close event is queued as a task, so it fires after close() returns, not during the call. Code on the line right after dlg.close() runs before your close listener does.
Guarding against invalid calls
Calling showModal() on a dialog that is already open as a non-modal throws an InvalidStateError. This usually happens when a click handler fires twice, or when show() was called earlier. Check open first:
function openDialog(dialog) {
if (!dialog.open) {
dialog.showModal();
}
}Calling close() on a dialog that is already closed does nothing, so it needs no guard.
Common errors
- Dialog never appears. The
<dialog>is hidden by default. Nothing shows it until a script callsshow()orshowModal(), or theopenattribute is present. - Dialog opens without a backdrop or focus trap. The
openattribute was used instead ofshowModal(). InvalidStateErroron open. The dialog was already open, often as a non-modal. Checkdialog.openfirst.- Stale
returnValue. The value from an earlier session is still set. Reset it before opening. - Code after
close()runs too early. Thecloseevent is asynchronous. Put follow-up work inside the listener.
Exercise
A dialog was opened with show(). Your code later calls showModal() on it and gets an error. What is the error, and how do you avoid it?
Show answer
The browser throws an InvalidStateError, because the dialog is already open as a non-modal. Check dialog.open before calling showModal(). If you want a modal, call close() first and then showModal().
Exercise
You call dlg.close('save') and the next line logs dlg.returnValue. Your close event listener logs the same property. Which log runs first, and why?
Show answer
The log on the line after close() runs first. The close event is queued as a task and fires after the current code finishes.