I have a modal jQuery dialog and another element that takes the ESC key event behind the dialog. When the jQuery Dialog is up, I don't want this ESC key event to propagate. What happens now is that when I click on ESC, it will close the dialog and trigger the ESC event handler on the background element.
How do I eat the ESC key event when a jQuery dialog is dismissed?
To detect escape key press, keyup or keydown event handler will be used in jquery. It will trigger over the document when the escape key will be pressed from the keyboard. keyup event: This event is fired when key is released from the keyboard.
On computer keyboards, the Esc key Esc (named Escape key in the international standard series ISO/IEC 9995) is a key used to generate the escape character (which can be represented as ASCII code 27 in decimal, Unicode U+001B, or Ctrl + [ ).
A dialog box is a floating window with a title and content area. This window can be moved, resized, and of course, closed using "X" icon by default. jQueryUI provides dialog() method that transforms the HTML code written on the page into HTML code to display a dialog box.
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/.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With