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);
});
.modal
created on the page (even dynamic modals)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