5 min read
ā¢Question 30 of 49mediumWhat is the Dialog Element?
Native modals and popups.
What You'll Learn
- Creating native modal dialogs
- showModal vs show methods
- Styling and accessibility
The Dialog Element
The <dialog> element creates native modal dialogs without JavaScript libraries.
Basic Usage
index.htmlHTML
<dialog id="myDialog">
<h2>Dialog Title</h2>
<p>This is a native dialog!</p>
<button onclick="this.closest('dialog').close()">Close</button>
</dialog>
<button onclick="document.getElementById('myDialog').showModal()">
Open Modal
</button>Methods
- showModal() - Modal dialog (blocks page)
- show() - Non-modal dialog
- close() - Hide the dialog
With Form
index.htmlHTML
<dialog id="confirmDialog">
<form method="dialog">
<p>Are you sure?</p>
<button value="cancel">Cancel</button>
<button value="confirm">Confirm</button>
</form>
</dialog>Styling
styles.cssCSS
dialog {
border: none;
border-radius: 8px;
padding: 20px;
}
dialog::backdrop {
background: rgba(0, 0, 0, 0.5);
}Features
- Escape key closes by default
- Focus trapping built-in
- Fully accessible