Universal / LIVE LAB

Back to Snippets

Accessible modal dialog with native focus and Escape behavior

A native dialog pattern with an explicit name, real close controls, backdrop-only dismissal, scroll containment, and opener focus restoration.

HTMLCSSJavaScript
Receipt: Escape works, the form scrolls, and backdrop clicks stay honest.

What this is

Open, close, scroll, and restore focus without rebuilding the browser.

Use this for compact forms, confirmations, media details, or any task that should temporarily sit above the page.

The browser handles focus entry, Escape, and focus restoration through showModal. The small script adds explicit actions and guards backdrop dismissal.

Use it

  • Keep the heading ID connected through aria-labelledby.
  • Wire your real save action before closing with the saved return value.
  • Test keyboard focus, Escape, the close buttons, backdrop clicks, zoom, and a short mobile viewport.

Make it yours

  • Replace the sample fields and save action while preserving the dialog label and close controls.
  • Adjust the maximum width and surface tokens without removing the viewport-bounded scroll area.

Reuse contract

Supported environments

  • Current Chrome, Edge, Firefox, and Safari
  • Native dialog support

Security notes

  • This demo stores nothing and makes no network requests.
  • Validate and authorize submitted form data again at the server boundary.
  • Close only when the dialog backdrop itself is targeted; child clicks must not dismiss it.
Loading the isolated live lab…