-1

I found this question about how to avoid the overlay of the second modal. So I have applied the @A1rPun fix:

$(document).on('show.bs.modal', '.modal', function () {
    var zIndex = 1040 + (10 * $('.modal:visible').length);
    $(this).css('z-index', zIndex);
    setTimeout(function() {
        $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
    }, 0);
});

$(document).on('hidden.bs.modal', '.modal', function () {
    $('.modal:visible').length && $(document.body).addClass('modal-open');
});

Now when I press the Esc button the modal form in the back is closed. However, the form ahead is the one that must be closed.

I have tried to fix it by adding some listener like the below code. But if I do this, sometimes both forms are closed at the same time. Maybe because there is another listener already.

$(document).ready(function() {
    $(window).keydown(function(event){
        if (event.keyCode == 27) {  // Esc code
            if ($('.modal-form').length > 0) {
                let z = 0;
                let modal_to_close = null;
                $('.modal-form').each(function () {
                    let current_z = parseInt($(this).css('z-index'), 10);
                    if (z < current_z) {
                        z = current_z;
                        modal_to_close = $(this);
                    }
                })
                modal_to_close.find('.close').click();
            }
        }
    });
});

How can I make this work well? Should I override the Bootstrap keydown listeners? How to do it?

enter image description here

Note: I am using Bootstrap v3.3.7

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
ChesuCR
  • 9,352
  • 5
  • 51
  • 114

1 Answers1

2

You need to use tabindex="-1" on your all modal, for example.

<div class="modal fade" id="myModal" tabindex="-1">

Working Fiddle

Pedram
  • 15,766
  • 10
  • 44
  • 73
  • 1
    When I press `Esc` in the front modal form then I need to click on the form that´s in the back to close it with `Esc` again. But it is enough for me, good approach – ChesuCR Jan 16 '18 at 22:03