HTMLDialogElement
TheHTMLDialogElement interface provides methods to manipulate<dialog> elements. It inherits properties and methods from theHTMLElement interface.
In this article
Instance properties
Also inherits properties from its parent interface,HTMLElement.
HTMLDialogElement.closedByA string that sets or returns the
closedbyattribute value of the<dialog>element, which indicates the types of user actions that can be used to close the dialog.HTMLDialogElement.openA boolean value reflecting the
openHTML attribute, indicating whether the dialog is available for interaction.HTMLDialogElement.returnValueA string that sets or returns the return value for the dialog.
Instance methods
Also inherits methods from its parent interface,HTMLElement.
HTMLDialogElement.close()Closes the dialog. An optional string may be passed as an argument, updating the
returnValueof the dialog.HTMLDialogElement.requestClose()Requests to close the dialog. An optional string may be passed as an argument, updating the
returnValueof the dialog.HTMLDialogElement.show()Displays the dialog modelessly, i.e., still allowing interaction with content outside of the dialog.
HTMLDialogElement.showModal()Displays the dialog as a modal, over the top of any other dialogs that might be present. Everything outside the dialog areinert with interactions outside the dialog being blocked.
Events
Also inherits events from its parent interface,HTMLElement.
Listen to these events usingaddEventListener() or by assigning an event listener to theoneventname property of this interface.
cancelFired when the dialog is requested to close, whether with the escape key, or via the
HTMLDialogElement.requestClose()method.closeFired when the dialog is closed, whether with the escape key, the
HTMLDialogElement.close()method, or via submitting a form within the dialog withmethod="dialog".
Examples
>Opening a modal dialog
The following example shows a button that, when clicked, uses theHTMLDialogElement.showModal() function to open a modal<dialog> containing a form.
While open, everything other than the modal dialog's contents is inert.You can click theCancel button to close the dialog (via theHTMLDialogElement.close() function), or submit the form via theConfirm button.
The example demonstrates how you might use all the "state change" events that can be fired on the dialog:cancel andclose, and the inherited eventsbeforetoggle, andtoggle.
HTML
<!-- pop-up dialog box, containing a form --><dialog> <form method="dialog"> <p> <label for="favAnimal">Favorite animal:</label> <select name="favAnimal"> <option></option> <option>Brine shrimp</option> <option>Red panda</option> <option>Spider monkey</option> </select> </p> <div> <button type="reset">Cancel</button> <button type="submit">Confirm</button> </div> </form></dialog><div> <button>Update details</button></div><pre></pre>#log { height: 150px; overflow: scroll; padding: 0.5rem; border: 1px solid black;}const logElement = document.querySelector("#log");function log(text) { logElement.innerText = `${logElement.innerText}${text}\n`; logElement.scrollTop = logElement.scrollHeight;}JavaScript
Showing the dialog
The code first gets objects for the<button> elements, the<dialog> element, and the<select> element.It then adds a listener to call theHTMLDialogElement.showModal() function when theUpdate button is clicked.
const updateButton = document.getElementById("updateDetails");const confirmButton = document.getElementById("submit");const cancelButton = document.getElementById("cancel");const dialog = document.getElementById("favDialog");const selectElement = document.getElementById("favAnimal");// Update button opens a modal dialogupdateButton.addEventListener("click", () => { dialog.showModal();});Cancel and confirm buttons
Next we add listeners to theConfirm andCancel buttonclick events.The handlers callHTMLDialogElement.close() with the selection value (if present) and no value, which in turn set the return value of the dialog (HTMLDialogElement.returnValue) to the selection value andnull, respectively.
// Confirm button closes dialog if there is a selection.confirmButton.addEventListener("click", () => { if (selectElement.value) { // Set dialog.returnValue to selected value dialog.close(selectElement.value); }});// Cancel button closes the dialog boxcancelButton.addEventListener("click", () => { dialog.close(); // Set dialog.returnValue to null});Callingclose() also fires theclose event, which we implement below by logging the return value of the dialog.If theConfirm button was clicked this should be the selected value in the dialog, otherwise it should benull.
dialog.addEventListener("close", (event) => { log(`close_event: (dialog.returnValue: "${dialog.returnValue}")`);});Cancel event
Thecancel event is fired when "platform specific methods" are used to close the dialog, such as theEsc key.It is also fired when theHTMLDialogElement.requestClose() method is called.The event is "cancelable" which means that we could use it to prevent the dialog from closing.Here we just treat the cancel as a "close" operation, and reset theHTMLDialogElement.returnValue to"" to clear any value that may have been set.
dialog.addEventListener("cancel", (event) => { log(`cancel_event: (dialog.returnValue: "${dialog.returnValue}")`); dialog.returnValue = ""; // Reset value});Toggle event
Thetoggle event (inherited fromHTMLElement) is fired just after a dialog has opened or closed (but before theclosed event).
Here we add a listener to log when the Dialog opens and closes.
Note:Thetoggle andbeforetoggle events may not be fired at dialog elements on all browsers.On these browser versions you can instead check theHTMLDialogElement.open property after attempting to open/close the dialog.
dialog.addEventListener("toggle", (event) => { log(`toggle_event: Dialog ${event.newState}`);});Beforetoggle event
Thebeforetoggle event (inherited fromHTMLElement) is a cancellable event that is fired just before a dialog is opened or closed.If needed, this can be used to prevent a dialog from showing, or to perform actions on other elements that are affected by the dialog open/close state, such as adding classes on them to trigger animations.
In this case we just log the old and new state.
dialog.addEventListener("beforetoggle", (event) => { log( `beforetoggle event: oldState: ${event.oldState}, newState: ${event.newState}`, ); // Call event.preventDefault() to prevent a dialog opening /* if (shouldCancel()) { event.preventDefault(); } */});Result
Try out the example below.Note that bothConfirm andCancel buttons result in theclose event being fired, and that the result should reflect the selected dialog option.
Specifications
| Specification |
|---|
| HTML> # htmldialogelement> |
| HTML> # event-beforetoggle> |
| HTML> # event-toggle> |
Browser compatibility
>api.HTMLDialogElement
api.HTMLElement.beforetoggle_event.dialog_elements
api.HTMLElement.toggle_event.dialog_elements
See also
- The HTML element implementing this interface:
<dialog>.