typestar

A dialog that behaves in HTML

The native dialog gives you the focus trap, the backdrop, and Escape to close.

<button type="button" id="open-prefs">Preferences</button>

<dialog id="prefs" aria-labelledby="prefs-title">
  <h2 id="prefs-title">Preferences</h2>
  <form method="dialog">
    <label for="theme">Theme</label>
    <select id="theme" name="theme">
      <option value="light">Light</option>
      <option value="dark">Dark</option>
    </select>
    <button value="cancel">Cancel</button>
    <button value="save">Save</button>
  </form>
</dialog>

<script>
  const prefs = document.getElementById('prefs');
  document.getElementById('open-prefs')
    .addEventListener('click', () => prefs.showModal());
  prefs.addEventListener('close', () => {
    console.log('closed with', prefs.returnValue);
  });
</script>

How it works

  1. showModal() makes the rest of the page inert and traps focus inside.
  2. aria-labelledby names the dialog from its own heading.
  3. A form with method="dialog" closes it and reports which button was used.

Keywords and builtins used here

The run, in numbers

Lines
23
Characters to type
660
Tokens
178
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 142 seconds.

Type this snippet

Step 4 of 4 in Focus and visibility, step 12 of 15 in Accessible HTML.

← Previous Next →