How to intercept jQuery Dialog ESC key event?

louis.luo picture louis.luo · May 6, 2012 · Viewed 32.4k times · Source

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?

Answer

TJ VanToll picture TJ VanToll · May 6, 2012

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