How to Make Multiple Modals Overlay in the Correct Order
In certain scenarios, it becomes necessary to display multiple modals on the same page. However, ensuring that each modal appears above the previous one can be challenging. This article explores a solution to overlay modals in the correct order, especially when more than two modals are involved.
Setup
In the given code snippet, multiple modals ("#myModal" and "#myModal2") are programmed to launch through button events. The issue lies in how the "#myModal2" modal appears behind the "#myModal" modal, rather than overlaying it.
Solution
The solution revolves around crafting a JavaScript function that efficiently manages the z-index of modals and their backdrops. This function, elaborated below, achieves the desired behavior by implementing the following steps:
Backdrop Z-Index Fix:
Scrollbar Fix:
Code Snippet
<code class="javascript">$(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')); }); $(document).on('hidden.bs.modal', '.modal', () => $('.modal:visible').length && $(document.body).addClass('modal-open'));</code>
Conclusion
Implementing this solution ensures that multiple modals overlay in the correct order, with the backdrop consistently appearing behind the active modal. This technique has been tested and works effectively for Bootstrap versions 3.1.0 to 3.3.5.
The above is the detailed content of How to Ensure Multiple Modals Overlay in the Correct Order in Bootstrap?. For more information, please follow other related articles on the PHP Chinese website!