Content · Web Development · HTML

HTML Dialog Showmodal and Focus Handling

Dialog Showmodal and Focus Handling: A modal dialog receives focus when opened and should restore a sensible focus location on close. Includes a practical HTML example and an explanation.

1 views Published Oct 19, 2026 Updated Oct 19, 2026 Admin

A useful interface does not need to be complicated. Start with native HTML, then add JavaScript only when you need it.

What You Need to Know


ShowModal makes a dialog modal and moves focus into the interaction. Test which element receives focus, how Escape behaves, and where focus goes after the dialog closes.

Try the Example


Take a look at the example. We’ll explain the important lines right below it.

<button id="open-instructions" type="button">Open instructions</button>
<dialog id="instructions">
    <h2>Instructions</h2>
    <p>Complete the quiz before closing this dialog.</p>
    <form method="dialog"><button>Close</button></form>
</dialog>
<script>
    const instructionsDialog = document.querySelector("#instructions");
    document.querySelector("#open-instructions").addEventListener("click", () => instructionsDialog.showModal());
</script>

Let’s Read the Code


  • <button>: The button offers an action; its type or command determines what happens.
  • <dialog>: Dialog provides a browser-managed dialog container; modal display may need showModal or a supported command.
  • id: An id uniquely identifies an element on this page.
  • type: Type changes what sort of control or resource the browser uses.

What the example shows: A modal dialog receives focus when opened and should restore a sensible focus location on close.

What Happens in the Browser?


When this example includes JavaScript, it supplies behavior that ordinary HTML does not automatically provide. Always think about a fallback.

What makes it interactive? Look for the JavaScript that finds an element and reacts to an event. HTML provides the initial controls and content; the script updates the page. Try removing the script to see which part still works natively.

Your Turn


Use keyboard navigation inside the dialog, close it, and check where focus returns.

Common Beginner Mistakes


  • Assuming new HTML syntax works in every browser without testing.
  • Do not hide a modal by changing CSS display alone; use the dialog API to close it properly.

Key Takeaways


  • ShowModal makes a dialog modal and moves focus into the interaction.
  • <button>: The button offers an action; its type or command determines what happens.
  • A meaningful HTML element is usually a stronger starting point than adding an ARIA role to a generic div. Also check what happens using only the keyboard.
Share this resourceSend this page to someone who may find it useful.