1

I was trying to find a simple function that would overlay modals on each other, so that one modal could trigger a second one. That means that the modals have to be one over the other using the z-index and therefore we need to do the same to the backdrop (the translucent overlay).

I found a few plugins, some answers using pure css etc. Here's mine in case it can help you, you don't have to add anything but these few lines !

YannickHelmut
  • 555
  • 1
  • 7
  • 20

1 Answers1

2
$('.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 !

YannickHelmut
  • 555
  • 1
  • 7
  • 20