The Jquery ui dialog box does not close with the `Escape` key

advertisements

When a user opens dialog, there are a bunch of ajax requests that have to be processed and therefore i have a second dialog that just displays loading information and closes once all the requests have been processed.

I am not able to close the user opened dialog with Escape key once it has opened. I have to click on the the dialog itself before I can use escape.

I have tried the following to assign the user opened dialog the focus after the loading dialog closes but to no avail, I still have to click on the dialog before it can close with the escape key.

$(document).ajaxStart(function () {
    // IF loading dialog is not allready being shown show it.
    if ($("#LoadingData").dialog('isOpen') === false) {
        $("#LoadingData").dialog('open');
    }
});

$(document).ajaxStop(function () {
    //Close the loading dialog once the requests have finished
    $("#LoadingData").dialog('close');
    //Find the user opened dialog
    $('.cmdialog').each(function () {
        if ($(this).dialog('isOpen')) {
            $(this).trigger('click');//set focus to dialog
            // have also replaced .trigger('click') with .focus() but to no avail
        }
    }).on('click', function() {
       //if click is triggerd set the focus of the dialog.
        if ($(this).prop('id') != 'LoadingData') {
            $(this).focus();
        }
    });
});

I have also tried setting the focus to the first element within the dialog with $('#DialogName:first-child').focus() and $('#DialogName:first-child').trigger('click') but this is also not working.

Any ideas as to why the focus is not set? Or am I misunderstanding/incorrectly using .focus() and .trigger('event')?

Thanks :)


Try the below code for close the dialog when Escap key is pressed:

$(document).keyup(function(e) {

  if (e.keyCode == 27) { $("#LoadingData").dialog('close'); }   // esc
});