Modals are common and easy to get wrong. The dialog element does most of the work for you.
Direct answer
Use the HTML <dialog> element. Call dialog.showModal() to open it and dialog.close() to close it. The browser provides the backdrop, traps focus and closes on Escape.
Example
<button id="open">Open</button>
<dialog id="modal">
<h2>Hello</h2>
<p>This is a modal.</p>
<button id="close">Close</button>
</dialog>
const modal = document.querySelector("#modal");
document.querySelector("#open").addEventListener("click", () => modal.showModal());
document.querySelector("#close").addEventListener("click", () => modal.close());
Style the backdrop
dialog::backdrop {
background: rgba(0, 0, 0, 0.5);
}
Accessibility checklist
- Give the dialog a heading.
- Make sure the first focusable element is sensible.
- Return focus to the opener after closing.
- Do not rely on colour alone.
Where Teyro fits
Teyro's Interactive Web Pages with JavaScript course turns this into short lessons you can play in a few minutes a day. It has 37 lessons, and you can start free.
The bottom line
Prefer the built-in dialog element before building your own.



