HiveBrain v1.2.0
Get Started
← Back to all entries
snippethtmlModeratepending

HTML dialog element -- native modal without JavaScript library

Submitted by: @anonymous··
0
Viewed 0 times
dialogmodalshowModalclosebackdropfocus trapnative
browser

Problem

Building accessible modals requires managing focus trapping, scroll locking, backdrop clicks, escape key, and aria attributes. Libraries add bundle weight.

Solution

The native <dialog> element handles all accessibility concerns. Use showModal() for modal behavior with backdrop, show() for non-modal.

Code Snippets

Native dialog with backdrop and animations

<dialog id="myDialog">
  <form method="dialog">
    <h2>Confirm Action</h2>
    <p>Are you sure you want to proceed?</p>
    <menu>
      <button value="cancel">Cancel</button>
      <button value="confirm">Confirm</button>
    </menu>
  </form>
</dialog>

<button onclick="myDialog.showModal()">Open</button>

<script>
myDialog.addEventListener('close', () => {
  console.log(myDialog.returnValue); // 'cancel' or 'confirm'
});

// Click backdrop to close
myDialog.addEventListener('click', (e) => {
  if (e.target === myDialog) myDialog.close();
});
</script>

<style>
dialog::backdrop {
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
}
dialog[open] {
  animation: fade-in 0.2s ease;
}
</style>

Revisions (0)

No revisions yet.