Sub topic 9
Closing when the user clicks the backdrop
This chapter assumes you can open a modal dialog with showModal(), close it with close(), and listen for the close event. It also assumes you know what ::backdrop is. If returnValue is unfamiliar, review the chapter on form method="dialog" first.
The browser does not do this for you
A modal dialog closes on Escape because the browser treats Escape as a close request. A click on the dimmed area outside the dialog is not treated the same way in every browser. Many people expect it to close the dialog, so you often add that behavior yourself. This is called light dismiss.
The behavior is optional. Some dialogs should not close on a stray click, such as a form with unsaved input or a confirmation for a destructive action. Add light dismiss when closing loses nothing, for example in an image preview or a help panel.
Why a click on the backdrop targets the dialog
::backdrop is a pseudo-element, so it cannot receive its own event listener. A click on the backdrop is reported with the <dialog> element as event.target. A click on content inside the dialog has the inner element (a button, a paragraph, an input) as its target.
That suggests a check: if event.target === dialog, the click was not on any child, so it must have landed on the backdrop. The check is only reliable if the dialog's own box contains nothing but its children. The browser's default stylesheet gives <dialog> padding. A click on that padding also has the dialog as its target, so it would wrongly close the dialog.
The fix is to remove the padding from the dialog and put it on an inner wrapper:
dialog {
border: none;
border-radius: 8px;
padding: 0;
max-width: min(32rem, 90vw);
}
dialog > .content {
padding: 1.5rem;
}
dialog::backdrop {
background: rgb(0 0 0 / 0.5);
}Now the wrapper covers the whole visible dialog box. The dialog element is the direct target only when the click is outside that box.
A complete example
This page opens a dialog and closes it when the user clicks outside it. The close event reports how the dialog ended.
<button id="open">Show details</button>
<dialog id="dlg" aria-labelledby="dlg-title">
<div class="content">
<h2 id="dlg-title">Order details</h2>
<p>Order #1042 shipped on Monday.</p>
<form method="dialog">
<button value="ok" autofocus>Close</button>
</form>
</div>
</dialog>
<style>
dialog {
border: none;
border-radius: 8px;
padding: 0;
max-width: min(32rem, 90vw);
}
dialog > .content {
padding: 1.5rem;
}
dialog::backdrop {
background: rgb(0 0 0 / 0.5);
}
</style>
<script>
const dlg = document.getElementById('dlg');
document.getElementById('open').addEventListener('click', () => {
dlg.returnValue = '';
dlg.showModal();
});
dlg.addEventListener('click', (event) => {
if (event.target === dlg) {
dlg.close('dismissed');
}
});
dlg.addEventListener('close', () => {
console.log('closed with:', dlg.returnValue || '(nothing)');
});
</script>Three details matter here.
- The
clicklistener is on the dialog, not on the document. Clicks inside the content bubble up to it, and theevent.targettest filters them out. dlg.close('dismissed')passes a string that becomesreturnValue. Yourclosehandler can then tell a backdrop dismissal from a click on the Close button, which gives"ok".dlg.returnValue = ''runs before eachshowModal()call. This is explained in the next section.
returnValue persists between openings
returnValue is a property of the dialog element. It keeps its last value until something changes it. If the dialog was closed with the "save" button last time and the user presses Escape this time, close fires and returnValue still reads "save". Your code would treat an Escape dismissal as a save.
Reset it before opening, as the example does. Then "" reliably means "closed without a choice". You can give the backdrop path its own value, such as "dismissed", if you want to tell it apart from Escape.
| How the dialog closed | `returnValue` after closing | Events fired |
|---|---|---|
| Submit button in `form method="dialog"` with `value="save"` | `"save"` | `close` |
| Escape key (after you reset it) | `""` | `cancel`, then `close` |
| Backdrop click with `dlg.close('dismissed')` | `"dismissed"` | `close` |
| `dlg.close()` with no argument (after you reset it) | `""` | `close` |
Calling close() from script does not fire cancel. Only a close request from the user or browser does, such as Escape. If you want a backdrop click to go through your cancel handler too, for example to confirm before discarding changes, use dlg.requestClose() where the browser supports it. It fires cancel first and lets the handler call preventDefault() to veto the close.
The drag problem
The simple check has a flaw that users will find quickly. Suppose someone selects text in an input, presses the mouse button inside the dialog, drags outward, and releases over the backdrop. The browser fires click on the nearest common ancestor of the element where the press began and the element where it ended. Here that ancestor is the dialog, so event.target === dlg is true and the dialog closes in the middle of a text selection.
Track where the press started and close only if both the press and the click were on the backdrop:
const dlg = document.getElementById('dlg');
let pressStartedOnBackdrop = false;
dlg.addEventListener('pointerdown', (event) => {
pressStartedOnBackdrop = event.target === dlg;
});
dlg.addEventListener('click', (event) => {
if (event.target === dlg && pressStartedOnBackdrop) {
dlg.close('dismissed');
}
pressStartedOnBackdrop = false;
});A press that began inside the content sets the flag to false, so the drag-out release is ignored. A press that began on the backdrop and ended on the backdrop sets the flag to true and closes the dialog.
One case remains. A keyboard click, such as pressing Enter on a button, may fire click without a preceding pointerdown. The flag is false in that case, which is correct because the target is a button, not the dialog.
Flowchart of the decision
Alternative: a bounds check
If you cannot remove the dialog's padding, you can compare the click position with the dialog's rectangle instead of checking the target:
const dlg = document.getElementById('dlg');
dlg.addEventListener('click', (event) => {
if (event.clientX === 0 && event.clientY === 0) return; // keyboard-triggered click
const rect = dlg.getBoundingClientRect();
const inside =
event.clientX >= rect.left &&
event.clientX <= rect.right &&
event.clientY >= rect.top &&
event.clientY <= rect.bottom;
if (!inside) {
dlg.close('dismissed');
}
});The first line guards against a real trap. A click triggered from the keyboard, such as Enter on a button, usually reports clientX and clientY as 0. That point is outside the dialog, so without the guard every keyboard activation would close it.
The bounds check also suffers from the drag problem, and the pointerdown flag fixes it the same way. For most pages the wrapper approach is simpler and has fewer failure modes, so prefer it.
The closedby attribute
Newer browsers have a declarative option. The closedby attribute states which close requests a dialog accepts:
| Value | Meaning |
|---|---|
| `any` | Escape and clicks outside the dialog both close it |
| `closerequest` | Only close requests such as Escape close it. This is the default for modal dialogs |
| `none` | The user cannot close it. Your code must call `close()` |
<dialog id="help" closedby="any" aria-labelledby="help-title">
<h2 id="help-title">Keyboard shortcuts</h2>
<p>Press ? to open this panel.</p>
<form method="dialog">
<button>Close</button>
</form>
</dialog>When closedby="any" is supported, the backdrop handler is not needed. Support is not universal yet, so check current browser compatibility data before relying on it. You can feature-detect it and install the script fallback only when needed:
const help = document.getElementById('help');
if (!('closedBy' in HTMLDialogElement.prototype)) {
help.addEventListener('click', (event) => {
if (event.target === help) help.close('dismissed');
});
}This fallback assumes the same padding-free layout described earlier. Dismissals through closedby follow the browser's own rules, so test the drag-out behavior in each browser you support.
Pitfalls
- Padding left on the dialog. Clicks on the padding close the dialog. Move padding to an inner wrapper.
- No padding reset on
::backdropassumptions. Do not try to listen on::backdrop. It has no event target of its own. - Stale
returnValue. Reset it before eachshowModal(). - Light dismiss on forms with unsaved data. Either skip it, or call
requestClose()and confirm in thecancelhandler. - Non-modal dialogs. A dialog opened with
show()has no backdrop. A click outside it never reaches the dialog element, so this technique does nothing there. - Only mouse users covered. Keep a visible Close button. Keyboard users close the dialog with Escape or a button, and touch users may not realize that tapping outside closes it.
Exercises
Exercise
A dialog uses the default browser padding. A user clicks the empty margin just inside the dialog's visible edge, and the dialog closes even though the click was not on the backdrop. What causes this, and what is the fix?
Show answer
The default stylesheet gives the dialog element its own padding. A click on that padding has the dialog as its target, which the handler cannot tell apart from a backdrop click. Set padding: 0 on the dialog and put the padding on an inner wrapper element, so that only the backdrop area targets the dialog itself.
Exercise
A user selects text in an input inside a dialog, drags the pointer past the dialog's edge, and releases the button. The dialog closes. Explain why, and write the two small changes that prevent it.
Show answer
The click event fires on the nearest common ancestor of the press target and the release target. That ancestor is the dialog, so event.target === dlg is true. Add a pointerdown listener that sets pressStartedOnBackdrop = event.target === dlg, and close in the click handler only when event.target === dlg && pressStartedOnBackdrop. Reset the flag afterward.
Exercise
Your close handler logs returnValue. The user saves the form once, then reopens the dialog and presses Escape. The log shows "save" again. What went wrong, and how do you fix it?
Show answer
returnValue keeps its previous value, and Escape does not set a new one. Reset it with dlg.returnValue = '' before each call to showModal(). Then an empty string means the dialog closed without a choice.