How to intercept jQuery Dialog ESC key event?
Internally jQuery UI's dialog's closeOnEscape
option is implemented by attaching a keydown listener to the document itself. Therefore, the dialog is closed once the keydown event has bubbled all the way to the top level.
So if you want to keep using the escape key to close the dialog, and you want to keep the escape key from propagating to parent nodes, you'll need to implement the closeOnEscape
functionality yourself as well as making use of the stopPropagation
method on the event object (see MDN article on event.stopPropagation).
(function() {
var dialog = $('whatever-selector-you-need')
.dialog()
.on('keydown', function(evt) {
if (evt.keyCode === $.ui.keyCode.ESCAPE) {
dialog.dialog('close');
}
evt.stopPropagation();
});
}());
What this does is listen for all keydown events that occur within the dialog. If the key pressed was the escape key you close the dialog as normal, and no matter what the evt.stopPropagation
call keeps the keydown from bubbling up to parent nodes.
I have a live example showing this here - http://jsfiddle.net/ud9KL/2/.
You can use the following
$(document).keyup(function (e) {
if (e.keyCode == 27) {
$('#YourDialogID').dialog('close')
}
});
You need closeOnEscape...
Example code:
$(function() {
$("#popup").dialog({
height: 200,
width: 400,
resizable: false,
autoOpen: true,
modal: true,
closeOnEscape: false
});
});
See it live: http://jsfiddle.net/vutdV/