$('.modal').on('show.bs.modal', function() {
var nModals = $('.modal.in').length;
$(this).attr('data-nmodals', nModals+1);
backdropStack(nModals);
});
function backdropStack(nModals) {
setTimeout(function() {
$('.modal-backdrop').each(function() {
if(!$(this).attr('data-nmodals')) {
$(this).attr('data-nmodals', nModals+1);
}
});
modalStack();
}, 100);
};
function modalStack() {
$('.modal').each(function() {
$n = $(this).data('nmodals');
$z = $(this).css('z-index');
$(this).css('z-index', $n*$z);
});
$('.modal-backdrop').each(function() {
$n = $(this).data('nmodals');
$z = $(this).css('z-index');
$(this).css('z-index', $n*$z);
});
}
Explanation: Each time a modal opens up, we count the existing modals and give them numbers to identify them (data-nmodals attribute). Since the backdrop appears a few seconds later, we wait 100 miliseconds before counting those in the backdropStack function.
Last but not least, the modalStack function multiplies the existing z-index value with the nModals number, which means that we could open up to 20 modals and this solution would still work out.
The limit being the maximum z-index accepted by CSS3 and browsers. If you get to that point... you probably have a UX design problem !