242

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.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Willian Bonho Daiprai
  • 2,635
  • 3
  • 12
  • 11
  • The question specifically relates to multiple modal backdrop overlays. For other "open multiple modals in Bootstrap" see: https://stackoverflow.com/questions/19528173/bootstrap-open-another-modal-in-modal/52114652#52114652 – Carol Skelly Apr 08 '21 at 12:53
  • https://stackoverflow.com/a/71031151/7186739 – Billu Feb 08 '22 at 09:06

35 Answers35

542

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

A1rPun
  • 16,287
  • 7
  • 57
  • 90
  • 1
    @A1rPun not working for me.. when i close the second modal.. the body become scrollable.. i used all your code.. :( – Vishal Aug 30 '16 at 06:23
  • 1
    Not worked in my environment with latest bs. I had to do: $('.modal-backdrop').last().not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack'); – metamagikum Dec 25 '16 at 18:06
  • 5
    I had to make a minor change (added `.not(this)` to the second line) to get it working with [bootstrap datepicker](https://bootstrap-datepicker.readthedocs.io/en/stable/) `var zIndex = 1040 + (10 * $('.modal:visible').not(this).length);` – benrwb Mar 08 '18 at 13:46
  • If two modals exist, then the first is removed and a third is added, the third will have the same z-index as the second as they both used a length of 2. I needed to factor in the last used z-index across the modals. – Murphybro2 Apr 09 '20 at 13:04
  • 9
    Works fine with BS4 latest – wobsoriano Apr 14 '20 at 05:57
  • 5
    You're a genius, this is incredible; if I could buy you a beer I would; Cheers. – Matt Drouillard Aug 27 '20 at 18:14
  • Superb! Works like a charm. – ɐsɹǝʌ ǝɔıʌ Nov 23 '21 at 10:46
  • 1
    Works fine with bs4 in Dec 2021 even. Thanks @A1rPun – Tahir Alvi Dec 07 '21 at 09:19
92

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'); 

    });        
});
Daan
  • 6,952
  • 4
  • 29
  • 36
Yermo Lamers
  • 1,911
  • 14
  • 25
  • 3
    Cool, however when one modal is closed, there appears two scrollbars -one for modal, second for whole page. Can be this solved? – Somnium Jul 21 '14 at 09:44
  • Are you using the latest bootstrap? – Yermo Lamers Jul 21 '14 at 13:00
  • Yes, you can see this in that example too if you download it and add a lot of text inside page. – Somnium Jul 28 '14 at 11:09
  • 3
    To deal with the extra scoll bar on close, you need to add class "modal-open" to the body in the hidden.bs.modal listener. – Lee Nov 18 '14 at 18:19
  • 5
    One issue I ran into was when the first modal was showing and needed a scrollbar, if I showed a second modal, it would remove the first modal's scrollbar and I was stuck with a clipped modal. To solve this, I just added this to my CSS, .modal { overflow-y: auto; } – ScubaSteve Nov 19 '14 at 22:33
  • Works well. I had to change the way it attaches to events to this form `$(document).on('---event---', '.modal', function() ...` instead of `$('.modal').on('---event---', ...)` because the content was rendered after the document ready event. – Diego Jancic Apr 24 '18 at 17:41
  • 2
    I feel like this should be the accepted answer. Works flawlessly for me. – Matthew Goheen Jan 09 '19 at 16:45
  • I Loved it. Addon to this, `$('.modal:visible').length && $(document.body).addClass('modal-open');` in `hidden.bs.modal` function – sanjeev shetty Dec 31 '19 at 07:31
29

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.

27

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');
});
  • 7
    One problem that remains here is that if you close out the second modal and your page has enough text to exceed the browser size, you end up with weird scrollbar behavior. You have to also restore the `modal-open` class on the body element: http://jsfiddle.net/vkyjocyn/ – StriplingWarrior Aug 11 '14 at 21:39
24

A simple solution for Bootstrap 4.5

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

.modal-backdrop.fade {
  opacity: 0;
}
Ricardo Canelas
  • 2,280
  • 26
  • 21
  • 4
    I combined your css with javascript fixes for bootstrap multiple modal not scrolling issue https://github.com/nakupanda/bootstrap3-dialog/issues/70#issuecomment-721108599, the stackOverflow issue: https://stackoverflow.com/a/64662694/423356 – kite Nov 04 '20 at 06:51
  • 2
    This solution works for Bootstrap 5 as well. Thank you Ricardo! – Nalin Jayasuriya Feb 27 '21 at 20:29
  • 3
    Wow this is crazy simple! Bootstrap team really should just use this! – Mu-Tsun Tsai Jan 23 '22 at 14:31
13

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));
jhay
  • 139
  • 1
  • 4
  • Nice solution. I expect the backdrop to go darker when you have multiple modals but I can see why you wouldn't want it. @AndyBurton Can you please let me know what my solution is missing? – A1rPun Feb 17 '16 at 15:59
  • @A1rPun upon opening and closing the 2nd modal the scroll bars which allowed scrolling in the 1st modal were removed. IIRC this looked to be because the class on the body was removed when the 2nd modal was closed. – Andy Burton Feb 18 '16 at 17:48
  • @AndyBurton I handle the solution to that problem as well. – A1rPun Feb 19 '16 at 08:12
12

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);
}
michal.jakubeczy
  • 8,221
  • 1
  • 59
  • 63
11

When solving Stacking modals scrolls the main page when one is closed 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.

Community
  • 1
  • 1
Bass Jobsen
  • 48,736
  • 16
  • 143
  • 224
9

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.

Willian Bonho Daiprai
  • 2,635
  • 3
  • 12
  • 11
4

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

Ullas
  • 11,450
  • 4
  • 33
  • 50
Timber
  • 859
  • 9
  • 25
4

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.2 (Update 2023)

This version has changed a little because Bootstrap now auto hides any other open modals when a new one is opened. Therefore, z-index CSS won't work. However, with a little JS you can force the first modal to stay open by reshowing it when the 2nd one is shown... (Again, this is a hack as Bootstrap does not support multiple open modals)

const myModal = bootstrap.Modal.getOrCreateInstance('#myModal')
const myModal2El = document.getElementById('myModal2')

// when 2nd modal is shown, reshow 1st modal
myModal2El.addEventListener('show.bs.modal', event => {
    // force re-show of modal 1
    myModal.show()
})

https://codeply.com/p/mYhmJ2fNau


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

Carol Skelly
  • 351,302
  • 90
  • 710
  • 624
  • 3
    Ok, that's great, but I put a third modal and it not works. I have some scripts that generate it (like alerts, search boxes, etc) and I can have 3 opened modals at once (until i know). I'm not good with css, sorry if i loose something. There is the code: http://bootply.com/86975 – Willian Bonho Daiprai Oct 10 '13 at 22:02
4

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', '');
});
devnomic
  • 697
  • 8
  • 11
4

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');
});
Ricardo Yubal
  • 374
  • 3
  • 8
3

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

2

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');
Netloh
  • 4,338
  • 4
  • 25
  • 38
nuEn
  • 71
  • 3
2

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; 
}
Liran Barniv
  • 1,320
  • 1
  • 10
  • 10
2

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" ... />
reformed
  • 4,505
  • 11
  • 62
  • 88
2

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>
Christopher
  • 3,124
  • 2
  • 12
  • 29
2

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
Radim Kleinpeter
  • 108
  • 2
  • 11
1

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>
...
paulalexandru
  • 9,218
  • 7
  • 66
  • 94
1

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'));
});
dotcomly
  • 2,154
  • 23
  • 29
1

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#

Deano
  • 11,582
  • 18
  • 69
  • 119
Ivan
  • 2,316
  • 2
  • 24
  • 22
1

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

Guntar
  • 473
  • 8
  • 23
1

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.

Joery
  • 741
  • 7
  • 5
0

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);

});
citxx
  • 2,525
  • 17
  • 40
0

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
0

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.

Jason Parker
  • 4,960
  • 4
  • 41
  • 52
0

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.

Amer Sawan
  • 2,126
  • 1
  • 22
  • 40
0
$(window).scroll(function(){
    if($('.modal.in').length && !$('body').hasClass('modal-open'))
    {
              $('body').addClass('modal-open');
    }

});
stara_wiedzma
  • 31
  • 1
  • 4
  • Code-only answers are often unhelpful in pointing to *why* the issue happened. You should include an explanation why it solves the issue. Please read [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) – FluffyKitten Aug 30 '17 at 12:11
0

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));
Synthie
  • 361
  • 2
  • 3
0

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');
Alper AKPINAR
  • 71
  • 3
  • 10
0

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);
  
  });
Prince Owusu
  • 31
  • 1
  • 4
0

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;
}
Billu
  • 2,733
  • 26
  • 47
-1

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.

-1

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.

degs
  • 37
  • 3