Multiple modals overlay

Willian Bonho Daiprai picture Willian Bonho Daiprai · Oct 10, 2013 · Viewed 255.5k times · Source

I need that the overlay shows above the first modal, not in the back.

Modal overlay behind

I tried to change the z-index of .modal-backdrop, but it becomes a mess.

In some cases I have more than two modals on the same page.

Answer

A1rPun picture A1rPun · Jul 23, 2014

After seeing many fixes for this, and none of them were exactly what I needed I've came up with a even shorter solution that is inspired by @YermoLamers & @Ketwaroo.

Backdrop z-index fix
This solution uses a setTimeout because the .modal-backdrop isn't created when the event show.bs.modal is triggered.

$(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);
});
  • This works for every .modal created on the page (even dynamic modals)
  • The backdrop instantly overlays the previous modal

Example jsfiddle

If you don't like the hardcoded z-index for any reason you can calculate the highest z-index on the page like this:

var zIndex = Math.max.apply(null, Array.prototype.map.call(document.querySelectorAll('*'), function(el) {
  return +el.style.zIndex;
})) + 10;

Scrollbar fix
If you have a modal on your page that exceeds the browser height, then you can't scroll in it when closing an second modal. To fix this add:

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

Versions
This solution is tested with bootstrap 3.1.0 - 3.3.5