Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to intercept jQuery Dialog ESC key event?

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?

like image 303
louis.luo Avatar asked May 05 '12 23:05

louis.luo


People also ask

How to detect escape key press with jQuery?

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.

What is escape keycode?

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 + [ ).

What is dialog in jquery?

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.


1 Answers

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/.

like image 74
TJ VanToll Avatar answered Nov 16 '22 01:11

TJ VanToll