I wanted to do a similar but opposite thing - prevent the ui dialog closing if we hit ESC in a modal window opened from inside the dialog while the dialog is still open.
Thus if the modal window is open on top of the ui dialog then ESC must only close the modal window and leave the ui dialog open. I don't want to disable closeOnEscape for the dialog, just suppress it if another modal is open over it.
I had no joy with $(document).on("keydown", ...) or $dialog.on("keydown", ...) in jquery-ui-1.12.1. I call the widget methods _off and _on to remove and replace the original keydown event with my own intercept event where I can either do nothing or run the original handler code.
There may be a more elegant way to call the original keydown event without duplicating the code, but I have not figured that out yet.
I call PatchCloseOnEscape($dialog) just after creating it with $dialog.dialog(...).
/**
* Tedium required to prevent the jQuery-UI dialog closing when we hit the ESC key to close
* a modal window opened from the dialog while the dialog is still open.
*/
private static PatchCloseOnEscape($dialog: JQuery): void
{
// Get dialog widget
let dialog = $dialog.data("ui-dialog");
// Remove original keydown event
dialog._off(dialog.uiDialog, "keydown");
// Add our new keydown event
dialog._on(dialog.uiDialog, {
keydown: function (event)
{
// Only close on escape if a modal window is not showing.
if (<check if modal window is open> == true)
{
return;
}
////////////////////////////////////////////////////////////////////////////////
// Copied from original keydown event in jquery-ui-1.12.1.js line 12278 - 12305
if (this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode &&
event.keyCode === (<any>$).ui.keyCode.ESCAPE)
{
event.preventDefault();
this.close(event);
return;
}
// Prevent tabbing out of dialogs
if (event.keyCode !== (<any>$).ui.keyCode.TAB || event.isDefaultPrevented())
{
return;
}
var tabbables = this.uiDialog.find(":tabbable"),
first = tabbables.filter(":first"),
last = tabbables.filter(":last");
if ((event.target === last[0] || event.target === this.uiDialog[0]) &&
!event.shiftKey)
{
this._delay(function ()
{
first.trigger("focus");
});
event.preventDefault();
} else if ((event.target === first[0] ||
event.target === this.uiDialog[0]) && event.shiftKey)
{
this._delay(function ()
{
last.trigger("focus");
});
event.preventDefault();
}
////////////////////////////////////////////////////////////////////////////////
}
});
}