Sub topic 5
Escape, the cancel event, and the close event
A modal dialog can close in several ways, and each way fires a slightly different set of events. This chapter explains what happens when the user presses Escape, when the cancel event fires, and what the close event tells you afterwards. It also covers how to intercept a close request and how to tell the ways of closing apart.
It assumes you can already open a dialog with showModal() and close it with close(), and that you are comfortable with DOM event listeners.
The two events in one sentence each
cancelfires when the user asks the browser to dismiss a modal dialog, most often with the Escape key. It is a request, and you can refuse it.closefires after the dialog has closed, by any route. It is a notification, and you cannot stop it.
Neither event bubbles. A listener on document or on a wrapper div will not see them in the normal bubbling phase, so attach listeners to the <dialog> element itself. If you must listen from an ancestor, use the capture phase: document.addEventListener('close', handler, true).
What Escape does
When a modal dialog is open and the user presses Escape, the browser runs these steps:
- It fires
cancelon the dialog. The event is cancelable. - If no listener called
preventDefault(), the browser closes the dialog. - Closing the dialog fires
close.
Without any JavaScript, Escape therefore closes a modal dialog. You get this behavior for free, which is one reason the element is worth using over a hand-built overlay.
A dialog opened with show() is different. It is non-modal, and the browser does not wire Escape to it. Pressing Escape inside a non-modal dialog does nothing by default, and no cancel event fires. If you want Escape to close a non-modal dialog, you must add a keydown listener yourself.
Watching both events
The smallest useful listener setup logs both events. This page is complete and runnable.
<button id="open">Open dialog</button>
<dialog id="dlg" aria-labelledby="dlg-title">
<h2 id="dlg-title">Event demo</h2>
<p>Press Escape, or use the buttons.</p>
<form method="dialog">
<button value="ok">OK</button>
</form>
<button id="plain-close" type="button">close() with no value</button>
</dialog>
<script>
const dlg = document.getElementById('dlg');
document.getElementById('open').addEventListener('click', () => {
dlg.returnValue = '';
dlg.showModal();
});
document.getElementById('plain-close').addEventListener('click', () => {
dlg.close();
});
dlg.addEventListener('cancel', (event) => {
console.log('cancel, cancelable:', event.cancelable);
});
dlg.addEventListener('close', () => {
console.log('close, returnValue:', JSON.stringify(dlg.returnValue));
});
</script>Try each route and watch the console:
- Escape logs
canceland thenclosewithreturnValueof"". - The OK button logs only
close, with"ok". - The "close() with no value" button logs only
close, with"".
The dlg.returnValue = '' line before showModal() matters. See the section on returnValue below.
Comparing the ways a dialog closes
| How the dialog closes | `cancel` fires | `close` fires | `returnValue` after |
|---|---|---|---|
| Escape on a modal dialog | Yes | Yes | Unchanged |
| `dialog.close()` | No | Yes | Unchanged |
| `dialog.close('x')` | No | Yes | `'x'` |
| Submit of `<form method="dialog">` | No | Yes | Value of the submit button used |
| `dialog.requestClose()` | Yes | Yes | Unchanged, or the argument if given |
| Dialog removed from the DOM while open | No | No | Not applicable |
Two rows are easy to get wrong:
- Calling
close()from your own code does not firecancel. Acancelhandler guards only the browser's dismissal paths, not your own code. - Removing an open dialog from the document fires neither event. If you clean up state in a
closehandler, remove dialogs only after closing them.
Intercepting Escape with preventDefault
Because cancel is cancelable, you can keep the dialog open. The typical use is protecting unsaved input.
<button id="open">Edit note</button>
<dialog id="dlg" aria-labelledby="dlg-title">
<form method="dialog">
<h2 id="dlg-title">Edit note</h2>
<textarea name="note" rows="4" cols="40" aria-label="Note"></textarea>
<p id="warn" hidden>Unsaved changes. Press Escape again to discard them.</p>
<menu>
<button value="discard" formnovalidate>Discard</button>
<button value="save">Save</button>
</menu>
</form>
</dialog>
<script>
const dlg = document.getElementById('dlg');
const form = dlg.querySelector('form');
const warn = document.getElementById('warn');
let dirty = false;
let warned = false;
document.getElementById('open').addEventListener('click', () => {
form.reset();
dirty = false;
warned = false;
warn.hidden = true;
dlg.returnValue = '';
dlg.showModal();
});
form.addEventListener('input', () => {
dirty = true;
warned = false;
warn.hidden = true;
});
dlg.addEventListener('cancel', (event) => {
if (dirty && !warned) {
event.preventDefault();
warned = true;
warn.hidden = false;
}
});
dlg.addEventListener('close', () => {
console.log('result:', dlg.returnValue || 'dismissed with Escape');
});
</script>The first Escape press after typing is blocked and shows a warning. A second Escape press is allowed through. Typing again re-arms the guard.
The handler uses two flags because the browser may not let you block Escape forever. Chrome and other Chromium browsers limit how often a page can cancel a close request. If the user presses Escape twice with no other interaction with the page in between, the second cancel event is not cancelable and the dialog closes. Check event.cancelable if your logic depends on it. The pattern above works either way, because the second press is the one you intend to allow.
The close event
close fires after the dialog has closed. Three details are useful in practice.
- The event is asynchronous. The browser queues it as a task, so it does not run in the middle of your
close()call. By the time your handler runs, theopenattribute is already gone anddlg.openisfalse. - It fires once per close. Calling
close()on a dialog that is already closed does nothing, and no event fires. - It cannot be canceled and carries no data. The event object has no useful properties. Read everything you need from the dialog itself, mainly
dlg.returnValue.
Because close fires for every route, it is the right place for cleanup and for acting on the result. Put logic that must always run, such as restoring page state or reading a result, in close. Put logic that decides whether to allow a dismissal in cancel.
returnValue and the Escape case
dialog.returnValue is a string. It is set by close('value'), or by submitting a <form method="dialog"> with a submit button that has a value. Escape does not touch it.
That leads to a common bug: returnValue persists between openings. If the user clicks Save once, returnValue is "save". If they later open the dialog again and press Escape, the close handler still sees "save" and treats the dismissal as a save.
The fix is to reset the value before each opening, as the examples above do:
dlg.returnValue = '';
dlg.showModal();After that, an empty returnValue in the close handler reliably means "closed without a choice". That covers Escape, a bare close(), and a button with no value.
A button with no value attribute sets returnValue to its text content, not to an empty string, in some situations. Check this in your target browsers, and give every button in a dialog form an explicit value.
Using requestClose and closedby
Two newer additions fill gaps in the older API. Both are recent, so check current browser support before relying on them. Neither is needed for the examples in this chapter.
dialog.requestClose(returnValue?) closes the dialog the way Escape would. It fires cancel first, honors preventDefault(), and then closes. Use it for your own Close buttons when you want the same guard logic to apply everywhere, so you do not need to duplicate the unsaved-changes check.
document.getElementById('close-btn').addEventListener('click', () => {
dlg.requestClose();
});If the browser lacks requestClose, you can fall back to close() after your own check.
The closedby attribute declares which dismissal methods the dialog accepts:
closedby="any"allows Escape and clicks outside the dialog.closedby="closerequest"allows Escape only, which is the default for modal dialogs.closedby="none"allows only explicit calls such asclose()or a form submission.
Where it is supported, closedby="any" replaces the backdrop-click script you will meet in a later chapter. Escape-based dismissal still produces the cancel and close events described here.
Common errors
- Listening for
cancelto detect every close. It fires only for dismissal requests. Useclosefor "the dialog is now closed". - Attaching listeners to a parent element. Neither event bubbles, so use the dialog element or the capture phase.
- Expecting Escape to close a
show()dialog. Non-modal dialogs get no built-in Escape handling. - Reading a stale
returnValue. Reset it before every open. - Showing a
confirm()inside acancelhandler. It blocks the page and behaves inconsistently with the browser's own limits on canceling. An in-dialog message, as in the unsaved-changes example, is safer and accessible. - Treating
cancelas the Cancel button. The Cancel button in the first chapter's form is an ordinary submit button withvalue="cancel". It triggersclose, not thecancelevent. The name overlap is a frequent source of confusion.
Exercise
A user opens a dialog, clicks Save (so returnValue becomes "save"), reopens the dialog later, and presses Escape. Your close handler logs "saved" again. Why does this happen, and what is the one-line fix?
Show answer
Escape fires cancel and then close, but it does not change returnValue, so the old value "save" is still there from the previous opening. Reset it before each opening with dlg.returnValue = '' just before calling dlg.showModal(). After that, an empty returnValue in the close handler means the dialog was dismissed without a choice.
Exercise
Which of these closing routes fire a cancel event: Escape on a modal dialog, dlg.close(), a submit of <form method="dialog">, and dlg.requestClose()? Which fire close?
Show answer
cancel fires for Escape and for requestClose(). It does not fire for close() or the form submission. close fires for all four routes.
Exercise
You attach document.addEventListener('close', handler) to log every dialog closing, but the handler never runs. Give two ways to fix it.
Show answer
The close event does not bubble, so a normal listener on document never receives it. Either attach the listener to each <dialog> element, or pass true as the third argument (document.addEventListener('close', handler, true)) so the listener runs in the capture phase.