Search code examples
javascripttwitter-bootstrap-3bootstrap-modal

Focus of Bootstrap Modal dialog when opening two nested modal lost


I have two modal which was opened in nested way. The ESCAPE keyboard only works in the closing of the second dialog. The first dialog does not close via keyboard unless I click on the dialog again to regain the focus. I am trying to restore the focus of the modal to the first dialog. So the user can do a consecutive [ESCAPE] - [ESCAPE] key to close both dialog. Both have tabindex="-1".

First dialog was called inside the main js file.

$('#firstDialog').modal({
    cache: false,
    backdrop: 'static'
}, 'show');

Second dialog was called inside an event of a button in the first dialog

$('#secondDialog').modal({
    cache: false,
    backdrop: 'static'
}, 'show');

I tried the following, to manually set the activeElement when second dialog is closed. It does not seem to work.

$('#secondDialog').on('hidden.bs.modal', function(){
    document.activeElement = $('#firstDialog')[0];
});

I referred the solution in the following thread on setting the activeElement. Any ideas what object does bootstrap need to be focused to have the escape back automatically? https://github.com/twbs/bootstrap/issues/4854


Solution

  • Found out the answer minutes after formulating the question. Anyway, if others have any better solution than this, please give me a suggestion. My thought is it should work by default.

    $('#secondDialog').on('hidden.bs.modal', function(){
        $('#firstDialog').focus();
    });