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
showModal()makes the rest of the page inert and traps focus inside.aria-labelledbynames the dialog from its own heading.- A form with
method="dialog"closes it and reports which button was used.
Keywords and builtins used here
constdocument
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.
Step 4 of 4 in Focus and visibility, step 12 of 15 in Accessible HTML.