Back to Snippets

Native Dialog Modal with Backdrop Blur JS

A destructive action opens a confirmation modal. Focus moves into the dialog, Escape or a click on the backdrop cancels, and the two buttons return a value the page can act on.

The modal is a native dialog element opened with showModal, which is what gives it the focus trap, the Escape key and the ::backdrop pseudo-element for free. The buttons sit inside a form with method set to dialog, so pressing one closes the dialog and stores that button's value in returnValue without any click handlers. A click on the backdrop reports the dialog itself as the target while a click inside reports its content, which is how the two are told apart.

The entrance is a CSS transition. @starting-style provides the hidden state to transition from, and allow-discrete on display and overlay lets the fade out finish before the dialog disappears.

1
#javascript
#css
#dialog
#modal
#popup
#confirm
#accessibility
#ui