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

  1. Click outside, if you set the closedby attribute to any. (currently Chromium-based browsers only)
    <dialog closedby="any">
       <h1>Hello World</h1>
    </dialog>

    Hello World

  2. A click event on a button that calls the close() method
    closeButton.addEventListener('click', e => {
       dialog.close();
    })

    Hello World

  3. 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();
       }
     }
    }

    Hello World

Close requests

  1. A button nested in a form with method=dialog
    <dialog>
       <form method="dialog">
         <button>close</button>
       </form>
       <h1>Hello World</h1>
    </dialog>

    Hello World

  2. Pressing the ESC key if you have a keyboard connected to the device.
  3. On Android, by pressing the back button.
  4. With TalkBack on Android, by doing the “back” gesture (swipe down and right).
  5. A game controller's canonical “back” button, such as the circle button on a DualShock gamepad. (I haven't tested that)
  6. (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).

Hello World

And finally, all methods combined: