Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save trungnghia112/5821f2e6515971d9afec51dd659e68af to your computer and use it in GitHub Desktop.
Save trungnghia112/5821f2e6515971d9afec51dd659e68af to your computer and use it in GitHub Desktop.

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

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.7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment