Lesson 6 of 9
Dialog Element & Native Modals
The <dialog> element is a native HTML element for creating modal dialogs and popups - without any JavaScript libraries. It provides focus trapping, Escape key handling, backdrop overlay, and proper ARIA semantics automatically. This replaces the need for custom modal components in many cases.
Using the Dialog Element
The <dialog> element has two display modes:
1. showModal() - Opens as a true modal:
• Page behind becomes inert (unclickable)
• Backdrop appears (styleable with ::backdrop)
• Focus is trapped inside (Tab cycles within dialog)
• Escape key closes it
• Returns a value via <form method='dialog'>
2. show() - Opens as a non-modal popup:
• Page behind remains interactive
• No backdrop
• No focus trapping
Closing methods:
• <form method='dialog'> - Buttons inside this form close the dialog
• dialog.close() - Close programmatically with JavaScript
• Escape key (modal only) - Automatically handled
The returnValue property contains the value of the button that closed the dialog.
Native dialog elements manage modal focus and backdrop trapping automatically
Dialog Example
<!DOCTYPE html>
<html>
<head>
<style>
dialog { border:none; border-radius:12px; padding:24px; max-width:400px; box-shadow:0 8px 32px rgba(0,0,0,0.2); }
dialog::backdrop { background:rgba(0,0,0,0.5); }
.btn { padding:10px 20px; border:none; border-radius:6px; cursor:pointer; font-weight:bold; }
.btn-primary { background:#229c6b; color:white; }
.btn-secondary { background:#ddd; color:#333; }
</style>
</head>
<body>
<button class="btn btn-primary" onclick="document.getElementById('myDialog').showModal()">
Open Dialog
</button>
<dialog id="myDialog">
<h2>Confirm Action</h2>
<p>Are you sure you want to proceed?</p>
<form method="dialog" style="display:flex;gap:8px;justify-content:flex-end">
<button value="cancel" class="btn btn-secondary">Cancel</button>
<button value="confirm" class="btn btn-primary">Confirm</button>
</form>
</dialog>
</body>
</html>Finished this lesson?