Home > Web Front-end > JS Tutorial > body text

How to Fix Overlapping Modals in Bootstrap: A Simple Solution with setTimeout and Z-Index Management.

Barbara Streisand
Release: 2024-10-26 02:14:02
Original
390 people have browsed it

How to Fix Overlapping Modals in Bootstrap:  A Simple Solution with setTimeout and Z-Index Management.

Multiple Modals Overlaying Easily

Encountering multiple modals overlaying each other can be frustrating, especially when you need the new modal to appear on top instead of behind the existing one. To resolve this issue, we'll delve into a solution inspired by two brilliant contributors: @YermoLamers and @Ketwaroo.

Backdrop Z-Index Fix

This solution relies on a setTimeout function, as the .modal-backdrop element is not yet created when the show.bs.modal event is triggered.

<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'));
});</code>
Copy after login

This approach has several advantages:

  • It applies to all .modal elements on the page, including dynamically created ones.
  • The backdrop immediately overlays the previous modal.

Z-Index Calculation

If you prefer not to hardcode the z-index, you can calculate the highest z-index on the page dynamically:

<code class="javascript">const zIndex = 10 +
  Math.max(...Array.from(document.querySelectorAll('*')).map((el) => +el.style.zIndex));</code>
Copy after login

Scrollbar Fix

In cases where a modal exceeds the browser height, you may encounter scrolling issues when closing an inner modal. To address this, add the following:

<code class="javascript">$(document).on('hidden.bs.modal', '.modal',
  () => $('.modal:visible').length && $(document.body).addClass('modal-open'));</code>
Copy after login

Compatibility

This solution has been tested with Bootstrap versions 3.1.0 - 3.3.5.

Example JSFiddle

[Example JSFiddle](https://jsfiddle.net/)

The above is the detailed content of How to Fix Overlapping Modals in Bootstrap: A Simple Solution with setTimeout and Z-Index Management.. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!