Dialog Dismissal
Dialogs can be dismissed in the following ways:
- Manually, by the user pressing the ESC key
- Programmatically, by calling
HTMLDialogElement#close
with an optional return value.
You can listen for the default gesture (typically [ENTER]) by registering for the submit
event on the form
:
Copied to your clipboard1function onsubmit(e) {2 dialog.close("ok");3 e.preventDefault();4}5form.onsubmit = onsubmit;
You should also register a click
handler for your "OK" and "Cancel" buttons:
Copied to your clipboard1const cancelButton = document.querySelector("#cancel");2cancelButton.addEventListener("click", () => dialog.close("reasonCanceled"));34const okButton = document.querySelector("#ok");5okButton.addEventListener("click", (e) => {6 onsubmit();7 e.preventDefault();8});
You can listen for the dialog's dismissal using the close
event on the dialog:
Copied to your clipboard1dialog.addEventListener("close", () => {2 // dialog is closed at this point3});
Preventing Dialog Dismissal
You can, in some cases, prevent a dialog dismissal. If the form calls preventDefault
on the submit
event, the dialog will fail to dismiss.
Tip
It is not possible to cancel a dismissal triggered by the ESC gesture.