Multiple modals overlay

JavascriptJqueryTwitter BootstrapTwitter Bootstrap-3Modal Dialog

Javascript Problem Overview


I need that the overlay shows above the first modal, not in the back.

Modal overlay behind

$('#openBtn').click(function(){
	$('#myModal').modal({show:true})
});

<a data-toggle="modal" href="#myModal" class="btn btn-primary">Launch modal</a>

<div class="modal" id="myModal">
	<div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
          <h4 class="modal-title">Modal title</h4>
        </div><div class="container"></div>
        <div class="modal-body">
          Content for the dialog / modal goes here.
          <br>
          <br>
          <br>
          <br>
          <br>
          <a data-toggle="modal" href="#myModal2" class="btn btn-primary">Launch modal</a>
        </div>
        <div class="modal-footer">
          <a href="#" data-dismiss="modal" class="btn">Close</a>
          <a href="#" class="btn btn-primary">Save changes</a>
        </div>
      </div>
    </div>
</div>
<div class="modal" id="myModal2" data-backdrop="static">
	<div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
          <h4 class="modal-title">Second Modal title</h4>
        </div><div class="container"></div>
        <div class="modal-body">
          Content for the dialog / modal goes here.
        </div>
        <div class="modal-footer">
          <a href="#" data-dismiss="modal" class="btn">Close</a>
          <a href="#" class="btn btn-primary">Save changes</a>
        </div>
      </div>
    </div>
</div>


<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/js/bootstrap.min.js"></script>

I tried to change the z-index of .modal-backdrop, but it becomes a mess.

In some cases I have more than two modals on the same page.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

I realize an answer has been accepted, but I strongly suggest not hacking bootstrap to fix this.

You can pretty easily achieve the same effect by hooking the shown.bs.modal and hidden.bs.modal event handlers and adjusting the z-index there.

Here's a working example

A bit more info is available here.

This solution works automatically with arbitrarily deeply stacks modals.

The script source code:

$(document).ready(function() {

    $('.modal').on('hidden.bs.modal', function(event) {
        $(this).removeClass( 'fv-modal-stack' );
        $('body').data( 'fv_open_modals', $('body').data( 'fv_open_modals' ) - 1 );
    });

    $('.modal').on('shown.bs.modal', function (event) {
        // keep track of the number of open modals
        if ( typeof( $('body').data( 'fv_open_modals' ) ) == 'undefined' ) {
            $('body').data( 'fv_open_modals', 0 );
        }
            
        // if the z-index of this modal has been set, ignore.
        if ($(this).hasClass('fv-modal-stack')) {
            return;
        }
        
        $(this).addClass('fv-modal-stack');
        $('body').data('fv_open_modals', $('body').data('fv_open_modals' ) + 1 );
        $(this).css('z-index', 1040 + (10 * $('body').data('fv_open_modals' )));
        $('.modal-backdrop').not('.fv-modal-stack').css('z-index', 1039 + (10 * $('body').data('fv_open_modals')));
        $('.modal-backdrop').not('fv-modal-stack').addClass('fv-modal-stack'); 

    });        
});

Solution 3 - Javascript

Combining A1rPun's answer with the suggestion by StriplingWarrior, I came up with this:

$(document).on({
	'show.bs.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);
	},
	'hidden.bs.modal': function() {
		if ($('.modal:visible').length > 0) {
			// restore the modal-open class to the body element, so that scrolling works
			// properly after de-stacking a modal.
			setTimeout(function() {
				$(document.body).addClass('modal-open');
			}, 0);
		}
	}
}, '.modal');

Works even for dynamic modals added after the fact, and removes the second-scrollbar issue. The most notable thing that I found this useful for was integrating forms inside modals with validation feedback from Bootbox alerts, since those use dynamic modals and thus require you to bind the event to document rather than to .modal, since that only attaches it to existing modals.

Fiddle here.

Solution 4 - Javascript

Something shorter version based off Yermo Lamers' suggestion, this seems to work alright. Even with basic animations like fade in/out and even crazy batman newspaper rotate. http://jsfiddle.net/ketwaroo/mXy3E/

$('.modal').on('show.bs.modal', function(event) {
	var idx = $('.modal:visible').length;
	$(this).css('z-index', 1040 + (10 * idx));
});
$('.modal').on('shown.bs.modal', function(event) {
	var idx = ($('.modal:visible').length) -1; // raise backdrop after animation.
	$('.modal-backdrop').not('.stacked').css('z-index', 1039 + (10 * idx));
	$('.modal-backdrop').not('.stacked').addClass('stacked');
});

Solution 5 - Javascript

A simple solution for Bootstrap 4.5

.modal.fade {
  background: rgba(0, 0, 0, 0.5);
}

.modal-backdrop.fade {
  opacity: 0;
}

Solution 6 - Javascript

I created a Bootstrap plugin that incorporates a lot of the ideas posted here.

Demo on Bootply: http://www.bootply.com/cObcYInvpq

Github: https://github.com/jhaygt/bootstrap-multimodal

It also addresses the issue with successive modals causing the backdrop to become darker and darker. This ensures that only one backdrop is visible at any given time:

if(modalIndex > 0)
    $('.modal-backdrop').not(':first').addClass('hidden');

The z-index of the visible backdrop is updated on both the show.bs.modal and hidden.bs.modal events:

$('.modal-backdrop:first').css('z-index', MultiModal.BASE_ZINDEX + (modalIndex * 20));

Solution 7 - Javascript

When solving https://stackoverflow.com/questions/27371918/stacking-modals-scrolls-the-main-page-when-one-is-closed/27379904#27379904 i found that newer versions of Bootstrap (at least since version 3.0.3) do not require any additional code to stack modals.

You can add more than one modal (of course having a different ID) to your page. The only issue found when opening more than one modal will be that closing one remove the modal-open class for the body selector.

You can use the following Javascript code to re-add the modal-open :

$('.modal').on('hidden.bs.modal', function (e) {
    if($('.modal').hasClass('in')) {
    $('body').addClass('modal-open');
    }    
});

In the case that do not need the backdrop effect for the stacked modal you can set data-backdrop="false".

Version 3.1.1. fixed Fix modal backdrop overlaying the modal's scrollbar, but the above solution seems also to work with earlier versions.

Solution 8 - Javascript

If you're looking for Bootstrap 4 solution, there's an easy one using pure CSS:

.modal.fade {
    background: rgba(0,0,0,0.5);
}

Solution 9 - Javascript

Finally solved. I tested it in many ways and works fine.

Here is the solution for anyone that have the same problem: Change the Modal.prototype.show function (at bootstrap.js or modal.js)

FROM:

if (transition) {
   that.$element[0].offsetWidth // force reflow
}   

that.$element
   .addClass('in')
   .attr('aria-hidden', false)

that.enforceFocus()

TO:

if (transition) {
    that.$element[0].offsetWidth // force reflow
}

that.$backdrop
   .css("z-index", (1030 + (10 * $(".modal.fade.in").length)))

that.$element
   .css("z-index", (1040 + (10 * $(".modal.fade.in").length)))
   .addClass('in')
   .attr('aria-hidden', false)

that.enforceFocus()

It's the best way that i found: check how many modals are opened and change the z-index of the modal and the backdrop to a higher value.

Solution 10 - Javascript

Try adding the following to your JS on bootply

$('#myModal2').on('show.bs.modal', function () {  
$('#myModal').css('z-index', 1030); })

$('#myModal2').on('hidden.bs.modal', function () {  
$('#myModal').css('z-index', 1040); })

Explanation:

After playing around with the attributes(using Chrome's dev tool), I have realized that any z-index value below 1031 will put things behind the backdrop.

So by using bootstrap's modal event handles I set the z-index to 1030. If #myModal2 is shown and set the z-index back to 1040 if #myModal2 is hidden.

Demo

Solution 11 - Javascript

My solution for bootstrap 4, working with unlimited depth of modals and dynamic modal.

$('.modal').on('show.bs.modal', function () {
    var $modal = $(this);
    var baseZIndex = 1050;
    var modalZIndex = baseZIndex + ($('.modal.show').length * 20);
    var backdropZIndex = modalZIndex - 10;
    $modal.css('z-index', modalZIndex).css('overflow', 'auto');
    $('.modal-backdrop.show:last').css('z-index', backdropZIndex);
});
$('.modal').on('shown.bs.modal', function () {
    var baseBackdropZIndex = 1040;
    $('.modal-backdrop.show').each(function (i) {
        $(this).css('z-index', baseBackdropZIndex + (i * 20));
    });
});
$('.modal').on('hide.bs.modal', function () {
    var $modal = $(this);
    $modal.css('z-index', '');
});

Solution 12 - Javascript

A1rPun's answer works perfectly after a minor modification (Bootstrap 4.6.0). My reputation won't let me comment, so I'll post an answer.

I just replaced every .modal:visible for .modal.show.

So, to fix the backdrop when opening multiple modals:

$(document).on('show.bs.modal', '.modal', function () {
    var zIndex = 1040 + (10 * $('.modal.show').length);
    $(this).css('z-index', zIndex);
    setTimeout(function() {
        $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
    }, 0);
});

And, to fix the scrollbar:

$(document).on('hidden.bs.modal', '.modal', function () {
    $('.modal.show').length && $(document.body).addClass('modal-open');
});

Solution 13 - Javascript

The solution to this for me was to NOT use the "fade" class on my modal divs.

Solution 14 - Javascript

Note: all answers are "hacks" since Bootstrap doesn't officially support multiple modals..

> "Bootstrap only supports one modal window at a time. Nested modals > aren’t supported as we believe them to be poor user experiences."

Here are some CSS workarounds/hacks...

Bootstrap 5 beta (Update 2021)

The default z-index for modals has changed again to 1060. Therefore, to override the modals and backdrop use..

.modal:nth-of-type(even) {
    z-index: 1062 !important;
}
.modal-backdrop.show:nth-of-type(even) {
    z-index: 1061 !important;
}

https://codeply.com/p/yNgonlFihM


The z-index for modals in Bootstrap 4 has changed again to 1050. Therefore, to override the open modals and backdrop use.

Bootstrap 4.x (Update 2018)

.modal:nth-of-type(even) {
    z-index: 1052 !important;
}
.modal-backdrop.show:nth-of-type(even) {
    z-index: 1051 !important;
}

https://codeply.com/p/29sH0ofTZb


Bootstrap 3.x (Original Answer)

Here is some CSS using nth-of-type selectors that seems to work:

    .modal:nth-of-type(even) {
        z-index: 1042 !important;
    }
    .modal-backdrop.in:nth-of-type(even) {
        z-index: 1041 !important;
    }

https://codeply.com/p/w8yjOM4DFb

Solution 15 - Javascript

Everytime you run sys.showModal function increment z-index and set it to your new modal.

function system() {
    
    this.modalIndex = 2000;

    this.showModal = function (selector) {
    	this.modalIndex++;

    	$(selector).modal({
			backdrop: 'static',
			keyboard: true
		});
    	$(selector).modal('show');
    	$(selector).css('z-index', this.modalIndex );    	
    }
    
}

var sys = new system();

sys.showModal('#myModal1');
sys.showModal('#myModal2');

Solution 16 - Javascript

No script solutions , using only css given you have two layers of modals, set the 2nd modal to a higher z index

.second-modal { z-index: 1070 }

div.modal-backdrop + div.modal-backdrop {
   z-index: 1060; 
}

Solution 17 - Javascript

If you want a specific modal to appear on top of another open modal, try adding the HTML of the topmost modal after the other modal div.

This worked for me:

<div id="modal-under" class="modal fade" ... />

<!--
This modal-upper should appear on top of #modal-under when both are open.
Place its HTML after #modal-under. -->
<div id="modal-upper" class="modal fade" ... />

Solution 18 - Javascript

Each modal should be given a different id and each link should be targeted to a different modal id. So it should be something like that:

<a href="#myModal" data-toggle="modal">
...
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>
...
<a href="#myModal2" data-toggle="modal">
...
<div id="myModal2" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>
...

Solution 19 - Javascript

EDIT: Bootstrap 3.3.4 has solved this problem (and other modal issues) so if you can update your bootstrap CSS and JS that would be the best solution. If you can't update the solution below will still work and essentially does the same thing as bootstrap 3.3.4 (recalculate and apply padding).

As Bass Jobsen pointed out, newer versions of Bootstrap have the z-index solved. The modal-open class and padding-right were still problems for me but this scripts inspired by Yermo Lamers solution solves it. Just drop it in your JS file and enjoy.

$(document).on('hide.bs.modal', '.modal', function (event) {
    var padding_right = 0;
    $.each($('.modal'), function(){
        if($(this).hasClass('in') && $(this).modal().data('bs.modal').scrollbarWidth > padding_right) {
            padding_right = $(this).modal().data('bs.modal').scrollbarWidth
        }
    });
    $('body').data('padding_right', padding_right + 'px');
});

$(document).on('hidden.bs.modal', '.modal', function (event) {
    $('body').data('open_modals', $('body').data('open_modals') - 1);
    if($('body').data('open_modals') > 0) {
        $('body').addClass('modal-open');
        $('body').css('padding-right', $('body').data('padding_right'));
    }
});

$(document).on('shown.bs.modal', '.modal', function (event) {
    if (typeof($('body').data('open_modals')) == 'undefined') {
        $('body').data('open_modals', 0);
    }
    $('body').data('open_modals', $('body').data('open_modals') + 1);
    $('body').css('padding-right', (parseInt($('body').css('padding-right')) / $('body').data('open_modals') + 'px'));
});

Solution 20 - Javascript

work for open/close multi modals

jQuery(function()
{
    jQuery(document).on('show.bs.modal', '.modal', function()
    {
        var maxZ = parseInt(jQuery('.modal-backdrop').css('z-index')) || 1040;

        jQuery('.modal:visible').each(function()
        {
            maxZ = Math.max(parseInt(jQuery(this).css('z-index')), maxZ);
        });
 
        jQuery('.modal-backdrop').css('z-index', maxZ);
        jQuery(this).css("z-index", maxZ + 1);
        jQuery('.modal-dialog', this).css("z-index", maxZ + 2);
    });
    
    jQuery(document).on('hidden.bs.modal', '.modal', function () 
    {
        if (jQuery('.modal:visible').length)
        {
            jQuery(document.body).addClass('modal-open');

           var maxZ = 1040;

           jQuery('.modal:visible').each(function()
           {
               maxZ = Math.max(parseInt(jQuery(this).css('z-index')), maxZ);
           });

           jQuery('.modal-backdrop').css('z-index', maxZ-1);
       }
    });
});

Demo

https://www.bootply.com/cObcYInvpq#

Solution 21 - Javascript

Check this out! This solution solved the problem for me, few simple CSS lines:

.modal:nth-of-type(even) {
z-index: 1042 !important;
}
.modal-backdrop.in:nth-of-type(even) {
    z-index: 1041 !important;
}

Here is a link to where I found it: Bootply Just make sure that the .modual that need to appear on Top is second in HTML code, so CSS can find it as "even".

Solution 22 - Javascript

For me, these simple scss rules worked perfectly:

.modal.show{
  z-index: 1041;
  ~ .modal.show{
    z-index: 1043;
  }
}
.modal-backdrop.show {
  z-index: 1040;
  + .modal-backdrop.show{
    z-index: 1042;
  }
}

If these rules cause the wrong modal to be on top in your case, either change the order of your modal divs, or change (odd) to (even) in above scss.

Solution 23 - Javascript

Based on the example fiddle of this answer, I updated it to support bootstrap 3 and 4 and fix all issues mentioned at the comments there. As i noticed them also, because i have some modals that have a timeout and close automatically.

It will not work with bootstrap 5. Bootstrap 5 doesn't store the bs.modal object anymore using node.data('bs.modal').

I suggest, viewing the snippet in full screen.

Bootstrap 3 using the same example as the answer mentiond, except that dialog 4 is modified.

!function () {
    var z = "bs.modal.z-index.base",
        re_sort = function (el) {
            Array.prototype.slice.call($('.modal.show,.modal.in').not(el))
                .sort(function (a, b) { // sort by z-index lowest to highest
                    return +a.style.zIndex - +b.style.zIndex
                })
                .forEach(function (el, idx) { // re-set the z-index based on the idx
                    el.style.zIndex = $(el).data(z) + (2 * idx);
                    const b = $(el).data('bs.modal')._backdrop || $(el).data("bs.modal").$backdrop;
                    if (b) {
                        $(b).css("z-index", +el.style.zIndex - 1);
                    }
                });
        };
    $(document).on('show.bs.modal', '.modal', function (e) {
        // removing the currently set zIndex if any
        this.style.zIndex = '';


        /*
         * should be 1050 always, if getComputedStyle is not supported use 1032 as variable...
         *
         * see https://getbootstrap.com/docs/4.0/layout/overview/#z-index and adjust the
         * other values to higher ones, if required
         *
         * Bootstrap 3: https:////netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.css
              .modal {
                [...]
                z-index: 1050;
                [...]
              }
              .modal-backdrop {
                [...]
                z-index: 1040;
                [...]
              }
         * Bootstrap 4: https://getbootstrap.com/docs/4.0/layout/overview/#z-index
         *
         *
         * lowest value which doesn't interfer with other bootstrap elements
         * since we manipulate the z-index of the backdrops too we need two for each modal
         * using 1032 you could open up to 13 modals without overlapping popovers
         */

        if (!$(this).data(z)) {
            let def = +getComputedStyle(this).zIndex; // 1050 by default
            def = 1032;
            $(this).data(z, def);
        }

        // resort all others, except this
        re_sort(this);

        // 2 is fine 1 layer for the modal, 1 layer for the backdrop
        var zIndex = $(this).data(z) + (2 * $('.modal.show,.modal.in').not(this).length);
        e.target.style.zIndex = zIndex;

        /*
         * Bootstrap itself stores the var using jQuery data property the backdrop 
         * is present there, even if it may not be attached to the DOM 
         * 
         * If it is not present, wait for it, using requestAnimationFrame loop
         */
        const waitForBackdrop = function () {
            try { // can fail to get the config if the modal is opened for the first time
                const config = $(this).data('bs.modal')._config || $(this).data('bs.modal').options;
                if (config.backdrop != false) {
                    const node = $(this).data('bs.modal')._backdrop ||
                        $(this).data("bs.modal").$backdrop;
                    if (node) {
                        $(node).css('z-index', +this.style.zIndex - 1);
                    } else {
                        window.requestAnimationFrame(waitForBackdrop);
                    }
                }
            } catch (e) {
                window.requestAnimationFrame(waitForBackdrop);
            }
        }.bind(this);
        waitForBackdrop();
    });
    $(document).on("shown.bs.modal", ".modal", function () {
        re_sort();
    });

    $(document).on('hidden.bs.modal', '.modal', function (event) {
        this.style.zIndex = ''; // when hidden, remove the z-index
        if (this.isConnected) {
          const b = $(this).data('bs.modal')._backdrop || $(this).data("bs.modal").$backdrop;
          if (b) {
              $(b).css("z-index", '');
          }
        }
        re_sort();
        // if still backdrops are present at dom - readd modal-open
        if ($('.modal-backdrop.show,.modal-backdrop.in').length)
            $(document.body).addClass("modal-open");
    })
}();

/* crazy batman newspaper spinny thing */
.rotate {
    transform:rotate(180deg);
    transition:all 0.25s;
}
.rotate.in {
    transform:rotate(1800deg);
    transition:all 0.75s;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet"/>


 <h2>Stacked Bootstrap Modal Example.</h2>
 <a data-toggle="modal" href="#myModal" class="btn btn-primary">Launch modal</a>

 <div class="modal fade" id="myModal">
   <div class="modal-dialog">
     <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
         <h4 class="modal-title">Modal 1</h4>

       </div>
       <div class="container"></div>
       <div class="modal-body">Content for the dialog / modal goes here.
         <br>
         <br>
         <br>
         <p>more content</p>
         <br>
         <br>
         <br> <a data-toggle="modal" href="#myModal2" class="btn btn-primary">Launch modal</a>

       </div>
       <div class="modal-footer"> <a href="#" data-dismiss="modal" class="btn">Close</a>
         <a href="#" class="btn btn-primary">Save changes</a>

       </div>
     </div>
   </div>
 </div>
 <div class="modal fade rotate" id="myModal2">
   <div class="modal-dialog">
     <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
         <h4 class="modal-title">Modal 2</h4>

       </div>
       <div class="container"></div>
       <div class="modal-body">Content for the dialog / modal goes here.
         <br>
         <br>
         <p>come content</p>
         <br>
         <br>
         <br> <a data-toggle="modal" href="#myModal3" class="btn btn-primary">Launch modal</a>

       </div>
       <div class="modal-footer"> <a href="#" data-dismiss="modal" class="btn">Close</a>
         <a href="#" class="btn btn-primary">Save changes</a>

       </div>
     </div>
   </div>
 </div>
 <div class="modal fade" id="myModal3">
   <div class="modal-dialog">
     <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
         <h4 class="modal-title">Modal 3</h4>

       </div>
       <div class="container"></div>
       <div class="modal-body">Content for the dialog / modal goes here.
         <br>
         <br>
         <br>
         <br>
         <br> <a data-toggle="modal" href="#myModal4" class="btn btn-primary">Launch modal</a>

       </div>
       <div class="modal-footer"> <a href="#" data-dismiss="modal" class="btn">Close</a>
         <a href="#" class="btn btn-primary">Save changes</a>

       </div>
     </div>
   </div>
 </div>
 <div class="modal fade" id="myModal4">
   <div class="modal-dialog">
     <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
         <h4 class="modal-title">Modal 4</h4>
       </div>
       <div class="container"></div>
       <div class="modal-body">
         <button onclick="$('#myModal').modal('hide');" class="btn btn-primary">hide #1</button>
         <button onclick="$('#myModal').modal('show');" class="btn btn-primary">show #1</button>
         <br>
         <button onclick="$('#myModal2').modal('hide');" class="btn btn-primary">hide #2</button>
         <button onclick="$('#myModal2').modal('show');" class="btn btn-primary">show #2</button>
         <br>
         <button onclick="$('#myModal3').modal('hide');" class="btn btn-primary">hide #3</button>
         <button onclick="$('#myModal3').modal('show');" class="btn btn-primary">show #3</button>
       </div>
       <div class="modal-footer"> <a href="#" data-dismiss="modal" class="btn">Close</a>
         <a href="#" class="btn btn-primary">Save changes</a>

       </div>
     </div>
   </div>
 </div>

Bootstrap 4 (see Bootstrap 3 snippet for commented code)

!function () {
    var z = "bs.modal.z-index.base",
        re_sort = function (el) {
            Array.prototype.slice.call($('.modal.show,.modal.in').not(el))
                .sort(function (a, b) {
                    return +a.style.zIndex - +b.style.zIndex
                })
                .forEach(function (el, idx) {
                    el.style.zIndex = $(el).data(z) + (2 * idx);
                    const b = $(el).data('bs.modal')._backdrop || $(el).data("bs.modal").$backdrop;
                    if (b) {
                        $(b).css("z-index", +el.style.zIndex - 1);
                    }
                });
        };
    $(document).on('show.bs.modal', '.modal', function (e) {
        this.style.zIndex = '';
        if (!$(this).data(z)) {
            let def = +getComputedStyle(this).zIndex;
            def = 1032;
            $(this).data(z, def);
        }
        re_sort(this);
        var zIndex = $(this).data(z) + (2 * $('.modal.show,.modal.in').not(this).length);
        e.target.style.zIndex = zIndex;

        const waitForBackdrop = function () {
            try {
                const config = $(this).data('bs.modal')._config || $(this).data('bs.modal').options;
                if (config.backdrop != false) {
                    const node = $(this).data('bs.modal')._backdrop ||
                        $(this).data("bs.modal").$backdrop;
                    if (node) {
                        $(node).css('z-index', +this.style.zIndex - 1);
                    } else {
                        window.requestAnimationFrame(waitForBackdrop);
                    }
                }
            } catch (e) {
                window.requestAnimationFrame(waitForBackdrop);
            }
        }.bind(this);
        waitForBackdrop();
    });
    $(document).on("shown.bs.modal", ".modal", function () {
        re_sort();
    });

    $(document).on('hidden.bs.modal', '.modal', function (event) {
        this.style.zIndex = '';
        if (this.isConnected) {
          const b = $(this).data('bs.modal')._backdrop || $(this).data("bs.modal").$backdrop;
          if (b) {
              $(b).css("z-index", '');
          }
        }
        re_sort();
        if ($('.modal-backdrop.show,.modal-backdrop.in').length)
            $(document.body).addClass("modal-open");
    })
}();


// creates dynamic modals i used this for stuff like 
// `enterSomething('stuff','to','display').then(...)`
!function() {
 let a = (i, a) => Array.prototype.forEach.call(a, (e) => $('#' + i + '-modal').find('.modal-body').append(e)),
        b = function () { $(this).remove() },
        c = (i, a) => Array.prototype.forEach.call(a, (e) => $('#' + i + '-modal-text-container').append(e)),
        r = () => 'dialog-' + (Date.now() + '-' + Math.random()).replace('.', '-');
this.createModal = function createModal() {
let id = r();
        $(document.body).append('<div class="modal fade" tabindex="-1" role="dialog" data-backdrop="static" aria-hidden="true" id="' + id + '-modal"><div class="modal-dialog d-flex modal-xl"><div class="modal-content align-self-stretch" style="overflow: hidden; max-height: -webkit-fill-available;"><div class="modal-header py-1"><h5 class="modal-header-text p-0 m-0"></h5><button id="' + id + '-modal-btn-close" type="button" tabindex="-1" class="close" data-dismiss="modal" aria-label="Close" title="Close"><span aria-hidden="true">&times;</span></button></div><div class="modal-body py-2"></div><div class="modal-footer py-1"><button type="button" class="btn btn-primary btn-sm" id="' + id + '-modal-btn-ok">Okay</button></div></div></div></div>');
        $('#' + id + '-modal-btn-ok').on('click', () => $('#' + id + '-modal').modal('hide'));
        $('#' + id + '-modal').on('shown.bs.modal', () => $('#' + id + '-modal-btn-ok').focus()).on('hidden.bs.modal', b).modal('show');
        $('#' + id + '-modal').find(".modal-header-text").html("Title");
        a(id, arguments);
        return new Promise((r) => $('#' + id + '-modal').on('hide.bs.modal', () => r()));
}
}();
function another() {
  createModal(
     $("<button class='btn mx-1'>Another...</button>").on("click", another),
     $("<button class='btn mx-1'>Close lowest</button>").on("click", closeLowest),
     $("<button class='btn mx-1'>Bring lowest to front</button>").on("click", lowestToFront),
     $("<p>").text($(".modal.show,.modal.in").length)
   ).then(() => console.log("modal closed"));
   // only for this example:
   $(".modal").last().css('padding-top', ($(".modal.show,.modal.in").length * 20) +'px');
}
function closeLowest() { 
   $(Array.prototype.slice.call($('.modal.show,.modal.in'))
     .sort(function (a, b) { // sort by z-index lowest to highest
        return +a.style.zIndex - +b.style.zIndex
     })).first().modal('hide');
}
function lowestToFront() {
   $(Array.prototype.slice.call($('.modal.show,.modal.in'))
     .sort(function (a, b) { // sort by z-index lowest to highest
        return +a.style.zIndex - +b.style.zIndex
     })).first().trigger('show.bs.modal');
}
another();

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<p>Use inspecter to check z-index values</p>

<button class="btn btn-outline-primary" onclick="another()">Click!</button>

Solution 24 - Javascript

Solution for Bootstrap 5 (pure JS).

Solution inspired by the answers of @A1rPun.

// On modal open
document.addEventListener('show.bs.modal', function(e) {

    // Get count of opened modals
    let modalsCount = 1;
    document.querySelectorAll('.modal').forEach(function(modalElement) {
        if (modalElement.style.display == 'block') {
            modalsCount++;
        }
    });

    // Set modal and backdrop z-indexes
    const zIndex = 1055 + 10 * modalsCount;
    e.target.style.zIndex = zIndex;
    setTimeout(() => {
        const backdropNotStacked = document.querySelector('.modal-backdrop:not(.modal-stack)');
        backdropNotStacked.style.zIndex = ('z-index', zIndex - 5);
        backdropNotStacked.classList.add('modal-stack');
    });

});

Explanation

  1. loop all visible modals (you cannot use the pseudoselector :visible, which is only in jquery)
  2. calculate new z-index. Default for Bootstrap 5 is 1055, so:

> default(1055) + 10 * number of opened modals

  1. set this new calculated z-index to the modal
  2. identify backdrop (backdrop without specified class - in our case .modal-stack)
  3. set this new calculated z-index -5 to the backdrop
  4. add class .modal-stack to the backdrop to prevent getting this backdrop while opening next modal

Solution 25 - Javascript

I had a similar scenario, and after a little bit of R&D I found a solution. Although I'm not great in JS still I have managed to write down a small query.

http://jsfiddle.net/Sherbrow/ThLYb/

<div class="ingredient-item" data-toggle="modal" data-target="#myModal">test1 <p>trerefefef</p></div>
<div class="ingredient-item" data-toggle="modal" data-target="#myModal">tst2 <p>Lorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem Ipsum</p></div>
<div class="ingredient-item" data-toggle="modal" data-target="#myModal">test3 <p>afsasfafafsa</p></div>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>





$('.ingredient-item').on('click', function(e){
    
   e.preventDefault();
    
    var content = $(this).find('p').text();

    $('.modal-body').html(content);
       
});

Solution 26 - Javascript

Add global variable in modal.js

var modalBGIndex = 1040; // modal backdrop background
var modalConIndex = 1042; // modal container data 

// show function inside add variable - Modal.prototype.backdrop

var e    = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })

modalConIndex = modalConIndex + 2; // add this line inside "Modal.prototype.show"

that.$element
    .show()
    .scrollTop(0)
that.$element.css('z-index',modalConIndex) // add this line after show modal 

if (this.isShown && this.options.backdrop) {
      var doAnimate = $.support.transition && animate

      modalBGIndex = modalBGIndex + 2; // add this line increase modal background index 2+

this.$backdrop.addClass('in')
this.$backdrop.css('z-index',modalBGIndex) // add this line after backdrop addclass

Solution 27 - Javascript

The other solutions did not work for me out of the box. I think perhaps because I am using a more recent version of Bootstrap (3.3.2).... the overlay was appearing on top of the modal dialog.

I refactored the code a bit and commented out the part that was adjusting the modal-backdrop. This fixed the issue.

    var $body = $('body');
    var OPEN_MODALS_COUNT = 'fv_open_modals';
    var Z_ADJUSTED = 'fv-modal-stack';
    var defaultBootstrapModalZindex = 1040;
        
    // keep track of the number of open modals                   
    if ($body.data(OPEN_MODALS_COUNT) === undefined) {
        $body.data(OPEN_MODALS_COUNT, 0);
    }

    $body.on('show.bs.modal', '.modal', function (event)
    {
        if (!$(this).hasClass(Z_ADJUSTED))  // only if z-index not already set
        {
            // Increment count & mark as being adjusted
            $body.data(OPEN_MODALS_COUNT, $body.data(OPEN_MODALS_COUNT) + 1);
            $(this).addClass(Z_ADJUSTED);

            // Set Z-Index
            $(this).css('z-index', defaultBootstrapModalZindex + (1 * $body.data(OPEN_MODALS_COUNT)));
            
            //// BackDrop z-index   (Doesn't seem to be necessary with Bootstrap 3.3.2 ...)
            //$('.modal-backdrop').not( '.' + Z_ADJUSTED )
            //        .css('z-index', 1039 + (10 * $body.data(OPEN_MODALS_COUNT)))
            //        .addClass(Z_ADJUSTED);
        }
    });
    $body.on('hidden.bs.modal', '.modal', function (event)
    {
        // Decrement count & remove adjusted class
        $body.data(OPEN_MODALS_COUNT, $body.data(OPEN_MODALS_COUNT) - 1);
        $(this).removeClass(Z_ADJUSTED);
        // Fix issue with scrollbar being shown when any modal is hidden
        if($body.data(OPEN_MODALS_COUNT) > 0)
            $body.addClass('modal-open');
    });

As a side note, if you want to use this in AngularJs, just put the code inside of your module's .run() method.

Solution 28 - Javascript

In my case the problem was caused by a browser extension that includes the bootstrap.js files where the show event handled twice and two modal-backdrop divs are added, but when closing the modal only one of them is removed.

Found that by adding a subtree modification breakpoint to the body element in chrome, and tracked adding the modal-backdrop divs.

Solution 29 - Javascript

$(window).scroll(function(){
    if($('.modal.in').length && !$('body').hasClass('modal-open'))
    {
              $('body').addClass('modal-open');
    }
    
});

Solution 30 - Javascript

Update: 22.01.2019, 13.41 I optimized the solution by jhay, which also supports closing and opening same or different dialogs when for example stepping from one detail data to another forwards or backwards.

(function ($, window) {
'use strict';

var MultiModal = function (element) {
    this.$element = $(element);
    this.modalIndex = 0;
};

MultiModal.BASE_ZINDEX = 1040;

/* Max index number. When reached just collate the zIndexes */
MultiModal.MAX_INDEX = 5;

MultiModal.prototype.show = function (target) {
    var that = this;
    var $target = $(target);
          
    // Bootstrap triggers the show event at the beginning of the show function and before
    // the modal backdrop element has been created. The timeout here allows the modal
    // show function to complete, after which the modal backdrop will have been created
    // and appended to the DOM.

    // we only want one backdrop; hide any extras
    setTimeout(function () {
        /* Count the number of triggered modal dialogs */
        that.modalIndex++;

        if (that.modalIndex >= MultiModal.MAX_INDEX) {
            /* Collate the zIndexes of every open modal dialog according to its order */
            that.collateZIndex();
        }

        /* Modify the zIndex */
        $target.css('z-index', MultiModal.BASE_ZINDEX + (that.modalIndex * 20) + 10);

        /* we only want one backdrop; hide any extras */
        if (that.modalIndex > 1) 
            $('.modal-backdrop').not(':first').addClass('hidden');

        that.adjustBackdrop();
    });
    
};

MultiModal.prototype.hidden = function (target) {
    this.modalIndex--;
    this.adjustBackdrop();

    if ($('.modal.in').length === 1) {

        /* Reset the index to 1 when only one modal dialog is open */
        this.modalIndex = 1;
        $('.modal.in').css('z-index', MultiModal.BASE_ZINDEX + 10);
        var $modalBackdrop = $('.modal-backdrop:first');
        $modalBackdrop.removeClass('hidden');
        $modalBackdrop.css('z-index', MultiModal.BASE_ZINDEX);
        
    }
};

MultiModal.prototype.adjustBackdrop = function () {        
    $('.modal-backdrop:first').css('z-index', MultiModal.BASE_ZINDEX + (this.modalIndex * 20));
};

MultiModal.prototype.collateZIndex = function () {

    var index = 1;
    var $modals = $('.modal.in').toArray();

    
    $modals.sort(function(x, y) 
    {
        return (Number(x.style.zIndex) - Number(y.style.zIndex));
    });     

    for (i = 0; i < $modals.length; i++)
    {
        $($modals[i]).css('z-index', MultiModal.BASE_ZINDEX + (index * 20) + 10);
        index++;
    };

    this.modalIndex = index;
    this.adjustBackdrop();
    
};

function Plugin(method, target) {
    return this.each(function () {
        var $this = $(this);
        var data = $this.data('multi-modal-plugin');

        if (!data)
            $this.data('multi-modal-plugin', (data = new MultiModal(this)));

        if (method)
            data[method](target);
    });
}

$.fn.multiModal = Plugin;
$.fn.multiModal.Constructor = MultiModal;

$(document).on('show.bs.modal', function (e) {
    $(document).multiModal('show', e.target);
});

$(document).on('hidden.bs.modal', function (e) {
    $(document).multiModal('hidden', e.target);
});}(jQuery, window));

Solution 31 - Javascript

Check count of modals and add the value to backdrop as z-index

	var zIndex = 1500 + ($('.modal').length*2) + 1;
	this.popsr.css({'z-index': zIndex});

	this.popsr.on('shown.bs.modal', function () {
		$(this).next('.modal-backdrop').css('z-index', zIndex - 1);
	});

	this.popsr.modal('show');

Solution 32 - Javascript

This code just works perfectly for bootstrap 4. The problem in other codes were how the modal-backdrop is selected. It'll be better if you used the jQuery next select on the actual modal after the modal has been shown.

$(document).on('show.bs.modal', '.modal', function () {
        var zIndex = 1040 + (10 * $('.modal').length);
        var model = $(this);
        model.css('z-index', zIndex);
        model.attr('data-z-index', zIndex);
    });

    $(document).on('shown.bs.modal', '.modal', function () {
        var model = $(this);
        var zIndex = model.attr('data-z-index');
        model.next('.modal-backdrop.show').css('z-index', zIndex - 1);
  
  });

Solution 33 - Javascript

z-index and modal-backdrop corrections with css

.modal.fade {
  z-index: 10000000 !important;
  background: rgba(0, 0, 0, 0.5);
}
.modal-backdrop.fade {
  opacity: 0;
}

Solution 34 - Javascript

Unfortunately I do not have the reputation to comment, but it should be noted that the accepted solution with the hardcoded baseline of a 1040 z-index seems to be superior to the zIndex calculation that tries to find the maximum zIndex being rendered on the page.

It appears that certain extensions/plugins rely on top level DOM content which makes the .Max calculation such an obscenely large number, that it can't increment the zIndex any further. This results in a modal where the overlay appears over the modal incorrectly (if you use Firebug/Google Inspector tools you'll see a zIndex on the order of 2^n - 1)

I haven't been able to isolate what the specific reason the various forms of Math.Max for z-Index leads to this scenario, but it can happen, and it will appear unique to a few users. (My general tests on browserstack had this code working perfectly).

Hope this helps someone.

Solution 35 - Javascript

This is a very old threat but, for me just worked to move the html code of the modal I want in the front at first place in file.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWillian Bonho DaipraiView Question on Stackoverflow
Solution 1 - JavascriptA1rPunView Answer on Stackoverflow
Solution 2 - JavascriptYermo LamersView Answer on Stackoverflow
Solution 3 - JavascriptSeven Deadly SinsView Answer on Stackoverflow
Solution 4 - JavascriptKetwaroo D. YaasirView Answer on Stackoverflow
Solution 5 - JavascriptRicardo CanelasView Answer on Stackoverflow
Solution 6 - JavascriptjhayView Answer on Stackoverflow
Solution 7 - JavascriptBass JobsenView Answer on Stackoverflow
Solution 8 - Javascriptmichal.jakubeczyView Answer on Stackoverflow
Solution 9 - JavascriptWillian Bonho DaipraiView Answer on Stackoverflow
Solution 10 - JavascriptTimberView Answer on Stackoverflow
Solution 11 - JavascriptdexcellView Answer on Stackoverflow
Solution 12 - JavascriptRicardo YubalView Answer on Stackoverflow
Solution 13 - JavascriptTony SchwartzView Answer on Stackoverflow
Solution 14 - JavascriptZimView Answer on Stackoverflow
Solution 15 - JavascriptnuEnView Answer on Stackoverflow
Solution 16 - JavascriptLiran BarnivView Answer on Stackoverflow
Solution 17 - JavascriptreformedView Answer on Stackoverflow
Solution 18 - JavascriptpaulalexandruView Answer on Stackoverflow
Solution 19 - JavascriptdotcomlyView Answer on Stackoverflow
Solution 20 - JavascriptIvanView Answer on Stackoverflow
Solution 21 - JavascriptGuntarView Answer on Stackoverflow
Solution 22 - JavascriptJoeryView Answer on Stackoverflow
Solution 23 - JavascriptChristopherView Answer on Stackoverflow
Solution 24 - JavascriptRadim KleinpeterView Answer on Stackoverflow
Solution 25 - Javascriptuser3500842View Answer on Stackoverflow
Solution 26 - JavascriptArpit PithadiaView Answer on Stackoverflow
Solution 27 - JavascriptClearCloud8View Answer on Stackoverflow
Solution 28 - JavascriptAmer SawanView Answer on Stackoverflow
Solution 29 - Javascriptstara_wiedzmaView Answer on Stackoverflow
Solution 30 - JavascriptSynthieView Answer on Stackoverflow
Solution 31 - JavascriptAlper AKPINARView Answer on Stackoverflow
Solution 32 - JavascriptPrince OwusuView Answer on Stackoverflow
Solution 33 - JavascriptdevView Answer on Stackoverflow
Solution 34 - JavascriptVincent PoliteView Answer on Stackoverflow
Solution 35 - JavascriptdegsView Answer on Stackoverflow