Sub topic 5
Escape, the cancel event, and the close event
This chapter assumes you can open a dialog with showModal(), know basic HTML forms, and can attach event listeners in JavaScript. It covers how a modal dialog ends, and which events fire along the way.
How a modal dialog gets closed
A modal dialog can close in three ways:
- Your code calls
dialog.close(). - A form with
method="dialog"is submitted. - The user presses Escape.
The first two are requests you make. The third comes from the browser. When the user presses Escape on a modal dialog, the browser fires a cancel event on the dialog. If nothing stops it, the browser then closes the dialog, and a close event fires.
The cancel event
cancel means "the user asked to dismiss this dialog." It fires for Escape. In browsers that support close requests, it also fires for the Android back gesture. It does not fire when your code calls close() or when a form submits.
The event is cancelable. Calling preventDefault() keeps the dialog open:
<dialog id="draft" aria-labelledby="draft-title">
<h2 id="draft-title">Write a note</h2>
<form method="dialog">
<textarea name="note" rows="4"></textarea>
<menu>
<button value="discard" formnovalidate>Discard</button>
<button value="save">Save</button>
</menu>
</form>
</dialog>
<button id="open">New note</button>
<script>
const draft = document.getElementById('draft');
const textarea = draft.querySelector('textarea');
document.getElementById('open').addEventListener('click', () => draft.showModal());
draft.addEventListener('cancel', (event) => {
if (textarea.value.trim() !== '') {
event.preventDefault();
console.log('Escape ignored: the note has unsaved text');
}
});
</script>If the textarea has text, Escape does nothing. If it is empty, the dialog closes.
Some browsers limit this. Chrome, for example, may ignore preventDefault() on cancel if the user presses Escape twice in a row without interacting with the page in between. This protects users from dialogs that cannot be dismissed. Do not rely on cancel to trap the user. Give them a visible way out, such as a Discard button.
The close event
close fires after the dialog has closed, no matter which of the three paths caused it. It is not cancelable. Use it for cleanup and for reading results.
const dialog = document.getElementById('draft');
dialog.addEventListener('close', () => {
if (dialog.returnValue === 'save') {
console.log('Saving the note');
} else {
console.log('Dismissed with:', JSON.stringify(dialog.returnValue));
}
});returnValue is a string on the dialog. Its value depends on how the dialog closed:
| How it closed | `returnValue` |
|---|---|
| `dialog.close('x')` | `"x"` |
| `dialog.close()` | Unchanged from before |
| Form submit with a button that has a `value` | That button's value |
| Escape | Unchanged from before |
"Unchanged from before" is the common trap. If the user saved once and later pressed Escape, returnValue is still "save", so your close handler would save again. Reset it when you open the dialog:
function openDraft() {
dialog.returnValue = '';
dialog.showModal();
}An empty string then means the user dismissed the dialog without choosing anything.
Putting the two events together
Use cancel to decide whether a dismissal is allowed. Use close to react once it has happened. Keep the two jobs apart, because cancel does not fire for every close and close cannot stop anything.
Quick reference
cancelis cancelable, fires for user dismissal, and happens before closing.closeis not cancelable, fires for every close, and happens after closing.- Reset
returnValuebefore eachshowModal()so stale values do not leak into the next result. - Always provide a visible control that closes the dialog.
Exercise
A user clicks Save in your dialog, which sets returnValue to "save". Later you call showModal() again and the user presses Escape. Your close handler checks returnValue === 'save'. What does it find, and how do you fix it?
Show answer
It still finds "save", because closing with Escape does not change returnValue, so the handler runs the save logic by mistake. Fix it by setting dialog.returnValue = '' before each showModal() call, so Escape leaves an empty string.
Exercise
You add a cancel listener that logs "dismissed". A user clicks a Cancel button inside a form with method="dialog". Does the log appear? Which event can you use to catch this case?
Show answer
No. Submitting a dialog form closes the dialog without firing cancel. The close event fires on every close path, so listen for close and check returnValue to tell the cases apart.