The JavaScript showModal() method
The showModal() method opens a <dialog> element as a modal — with a dimmed backdrop, focus trapped inside, and Escape-to-close — all built in. dialog.showModal() opens it; dialog.close() closes it. It's the native, accessible way to build modal dialogs without a library.
Overview
showModal() opens the native <dialog> element as a true modal, and it handles the hard parts of modals for free: it dims the page behind a backdrop, traps keyboard focus inside the dialog, makes the rest of the page inert (unclickable), and closes on the Escape key. Those are exactly the things people get wrong when hand-building modals, so the browser doing them is a big win for accessibility.
The API is small: dialog.showModal() opens it as a modal, dialog.show() opens it non-modally (no backdrop or focus trap), and dialog.close(returnValue) closes it. A nice touch is form integration — a <button> inside a <form method="dialog"> closes the dialog and sets its returnValue to the button's value, so you can tell which button was pressed.
You can style the dimmed backdrop with the CSS ::backdrop pseudo-element. The native dialog now has solid browser support and is the recommended approach over custom modal code — it's less code and more accessible. Reach for a library only if you need behavior the native element doesn't cover.
Syntax
dialog.showModal(); // open as a modal (backdrop + focus trap)
dialog.show(); // open non-modally
dialog.close(value); // close, optionally setting returnValue
dialog.returnValue; // what closed it (e.g. a form button's value)
Example
<button onclick="document.getElementById('dlg').showModal()" style="font:14px system-ui">Open dialog</button>
<dialog id="dlg" style="font:15px system-ui;border:0;border-radius:10px;padding:20px">
<p>This is a native modal dialog.</p>
<form method="dialog"><button>Close</button></form>
</dialog>
Best practices
- Use
showModal()(notshow()) for real modals — it adds the backdrop, focus trap and Escape handling. - Use a
<form method="dialog">so buttons close the dialog and setreturnValue. - Style the dimmed background with the CSS
::backdroppseudo-element. - Prefer the native
<dialog>over custom modal code — it's more accessible with less work.
Frequently asked questions
How do I open a modal dialog in JavaScript?
dialog.showModal() on a <dialog> element. It adds a backdrop, traps focus and closes on Escape automatically.What is the difference between showModal() and show()?
showModal() opens it as a modal (backdrop, focus trap, page inert); show() opens it non-modally with none of that.How do I close a dialog?
dialog.close(), press Escape, or use a button inside a <form method="dialog">.How do I style the dialog backdrop?
::backdrop pseudo-element on the dialog.