I’m first hearing about the CloseWatcher
API after running across Abdelrahman Awad’s blog post about it. The MDN docs are quite direct, making the purpose clear:
Some UI components have “close behavior”, meaning that the component appears, and the user can close it when they are finished with it. For example: sidebars, popups, dialogs, or notifications.
Users generally expect to be able to use a particular mechanism to close these elements, and the mechanism tends to be device-specific. For example, on a device with a keyboard it might be the Esc key, but Android might use the back button.
So rather than bind an closing action to the Esc
key, use this API, which normalizes that user action across platforms.
I also like how it automatically creates a “stack” of things to close. So if there are multiple closeable things open, a close event only closes the most recently open one. I made a demo to play with this (note the Chrome-n-friends only support!).
A video in case it doesn’t work on your browser: