Every website needs a modal sooner or later — a login box, a confirm dialog, an image viewer. The modern way to build one is the HTML dialog element, and it removes most of the work that used to make modals painful.
What you are building
A modal that opens from a button, closes from a button, from the Escape key, and from clicking outside it — with a dimmed background behind it.
The HTML: the dialog element
<button id="open-btn">Open modal</button>
<dialog id="my-modal">
<h2>Delete this item?</h2>
<p>This cannot be undone.</p>
<button id="close-btn">Cancel</button>
<button id="confirm-btn">Delete</button>
</dialog>
The JavaScript: two methods do everything
const modal = document.querySelector('#my-modal');
document.querySelector('#open-btn').addEventListener('click', () => {
modal.showModal();
});
document.querySelector('#close-btn').addEventListener('click', () => {
modal.close();
});
// Close when clicking the backdrop (outside the dialog box)
modal.addEventListener('click', (e) => {
if (e.target === modal) modal.close();
});
showModal() is the key: it opens the dialog on the top layer, dims the page behind it, traps focus inside, and closes on Escape — all built in. The old way needed a library for exactly these behaviours.
The CSS: style the backdrop
dialog {
border: none;
border-radius: 12px;
padding: 24px;
max-width: 400px;
}
dialog::backdrop {
background: rgba(0, 0, 0, 0.5);
}
The ::backdrop pseudo-element styles the dimmed area behind the dialog. Before the dialog element existed, developers had to build that overlay themselves.
The one thing to remember
Use showModal(), not show(). The plain show() method opens the dialog without the top layer, without the backdrop, and without focus trapping — and your modal will behave like a badly positioned box instead of a real dialog.
Top comments (0)