Solution inspired by the answers of @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() {
const zIndex = 1040 + 10 * $('.modal:visible').length;
$(this).css('z-index', zIndex);
setTimeout(() => $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack'));
});
- This works for every
.modal
created on the page (even dynamic modals) - The backdrop instantly overlays the previous modal
Example jsfiddle
z-index
If you don’t like the hardcoded z-index for any reason you can calculate the highest z-index on the page like this:
const zIndex = 10 +
Math.max(...Array.from(document.querySelectorAll('*')).map((el) => +el.style.zIndex));
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',
() => $('.modal:visible').length && $(document.body).addClass('modal-open'));
Versions
This solution is tested with bootstrap 3.1.0 – 3.3.5