The <dialog>
HTML element represents a dialog box or other interactive component, such as a dismissible alert, inspector, or subwindow.
This element includes the global attributes.
Warning: The tabindex
attribute must not be used on the <dialog>
element.
-
open
-
Indicates that the dialog is active and can be interacted with. When the open
attribute is not set, the dialog shouldn't be shown to the user. It is recommended to use the .show()
or .showModal()
methods to render dialogs, rather than the open
attribute.
The dialog
element still has usability issues with some forms of assistive technology. Because of this, it is advised to use an interim solution such as a11y-dialog as support continues to improve.
The following will render a modeless (non-modal) dialog. The "OK" button allows the dialog to be closed when activated. It is important to provide a mechanism to close a dialog within the dialog
element. For instance, the Esc key does not close modeless dialogs by default, nor can one assume that a user will even have access to a physical keyboard (e.g., someone using a touch screen device without access to a keyboard).
<dialog open>
<p>Greetings, one and all!</p>
<form method="dialog">
<button>OK</button>
</form>
</dialog>
This example opens a modal dialog that contains a form, when the "Update details" button is activated.
HTML
<dialog id="favDialog">
<form method="dialog">
<p><label>Favorite animal:
<select>
<option value="default">Choose...</option>
<option>Brine shrimp</option>
<option>Red panda</option>
<option>Spider monkey</option>
</select>
</label></p>
<div>
<button value="cancel">Cancel</button>
<button id="confirmBtn" value="default">Confirm</button>
</div>
</form>
</dialog>
<p>
<button id="updateDetails">Update details</button>
</p>
<output></output>
JavaScript
const updateButton = document.getElementById('updateDetails');
const favDialog = document.getElementById('favDialog');
const outputBox = document.querySelector('output');
const selectEl = favDialog.querySelector('select');
const confirmBtn = favDialog.querySelector('#confirmBtn');
if ( typeof favDialog.showModal !== 'function' ) {
favDialog.hidden = true;
}
updateButton.addEventListener('click', function onOpen() {
if (typeof favDialog.showModal === "function") {
favDialog.showModal();
} else {
outputBox.value = "Sorry, the <dialog> API is not supported by this browser.";
}
});
selectEl.addEventListener('change', function onSelect(e) {
confirmBtn.value = selectEl.value;
});
favDialog.addEventListener('close', function onClose() {
outputBox.value = favDialog.returnValue + " button clicked - " + (new Date()).toString();
});