Close requests, close watchers, and the dialog element
posted on
The latest version of Chrome (134) comes with a new light-dismiss behavior for the dialog element, which enables a native click-outside feature. That's fantastic! Reading the announcement, I wondered how many ways there are to close a dialog element.
The specification states that a user can send a close request to the user agent, indicating that the user wishes to close something currently being shown on the screen, such as a popover, menu, or dialog. There are also close watchers, which listen to other close or cancel actions.
My goal is to collect all close requests and watchers in this blog post. Please get in touch if anything is missing.
Close watchers
- Click outside, if you set the
closedby
attribute toany
. (currently Chromium-based browsers only)<dialog closedby="any"> <h1>Hello World</h1> </dialog>
- A click event on a button that calls the
close()
methodcloseButton.addEventListener('click', e => { dialog.close(); })
- A click event on a button that calls the
requestClose()
method. (currently Chromium-based browsers only)closeButton.addEventListener('click', e => { dialog.requestClose(); }) dialog.oncancel = (e) => { if (e.cancelable) { if (!confirm("Are you sure you want to close this?")) { e.preventDefault(); } } }
Close requests
- A button nested in a form with
method=dialog
<dialog> <form method="dialog"> <button>close</button> </form> <h1>Hello World</h1> </dialog>
- Pressing the
ESC key if you have a keyboard connected to the device. - On Android, by pressing the back button.
- With TalkBack on Android, by doing the “back” gesture (swipe down and right).
- A game controller's canonical “back” button, such as the circle button on a DualShock gamepad. (I haven't tested that)
- (The spec says, with VoiceOver on Safari, by doing the two-finger scrub "z" gesture, but in my tests that brings me back to the previous page).
And finally, all methods combined: