Struggling with overlaying Bootstrap modals on top of each other

This idea is inspired by the topic Multiple modals overlay

I am working on developing a folder modal that allows users to either 1) open an existing file or 2) create a new file within each folder modal.

To see how it functions, please run the code below. You'll need to interact with buttons and list items to trigger the modals.

However, instead of using dialogs, this operates in full-screen mode via Bootstrap.

https://i.sstatic.net/hlLf4.png

Clicking a button adds a folder item to the list. Clicking "This is folder ###" opens a modal as depicted here:

https://i.sstatic.net/Kz7CR.png

You can then proceed to create a file:

https://i.sstatic.net/gyWu4.png

The issue that needs to be addressed is when a file item is clicked, the file modal should overlay on top of the folder modal. Currently, they both close and do not remain visible simultaneously.

<!doctype html>
<html lang="en">

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4b6bbbba0a7a0a6b5a494e1fae6fae6">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous" -->


    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="45272a2a31363137243505706b776b77">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</head>

<body>

    <button class="btn btn-primary" id="addnewfolder">Create new folder</button>

    <ul class="list-group folder"></ul>

    <script>
        $("#addnewfolder").click(function(event) {

            var code = (Math.random() + 1).toString(36).substring(7)

            $(".folder").append(`<li class="list-group-item">
    <img src="https://img.icons8.com/officel/48/null/live-folder.png" class="float-start" />


    <div class="ms-5" data-bs-toggle="modal" href="#modal-toggle-${code}">This is folder ${code}<br />

        <div>
            <div class="modal fade" id="modal-toggle-${code}" aria-hidden="true" aria-labelledby="modal-toggleLabel" tabindex="-1">
                <div class="modal-dialog modal-fullscreen">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h1 class="modal-title fs-5" id="modal-toggleLabel">Inside Folder ${code}</h1>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <ul class="list-group file"></ul>
                            <button data-bs-target="#modal-toggle2" data-bs-toggle="modal" class="btn btn-primary file-${code}">Add File Inside ${code}</button>
                        </div>
                        <div class="modal-footer">
                            <button class="btn btn-primary">Save</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</li>`);
            //$(`#modal-toggle-${code}`).modal("show");

            $(`.file-${code}`).click(function(event) {
                        var dcode = Math.floor(Math.random() * 10);
                        $(".file").append(`<li class="list-group-item">
    <img src="https://img.icons8.com/cotton/64/null/happy-file.png" class="float-start" />




    <div class="ms-5">This is file inside ${code}-${dcode}<br />
        <small class="text-secondary">This is a ${code}-${dcode} item description</small>
        <div>
            <div class="modal fade" id="modal-toggle-${code}-${dcode}" aria-hidden="true" aria-labelledby="modal-toggleLabel" tabindex="-1">
                <div class="modal-dialog modal-fullscreen">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h1 class="modal-title fs-5" id="modal-toggleLabel">Inside Folder</h1>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            Hello World
                        </div>
                        <div class="modal-footer">
                            <button class="btn btn-primary">Save</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</li>`);
            
            //$(`#modal-toggle-${code}-${dcode}`).modal("show");

            });

        });
        
        
$(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'));
});

    </script>

</body>

Answer â„–1

Avoid stacking Bootstrap modals.

Bootstrap only allows one modal window to be open at a time. Nesting modals is not supported as it can lead to poor user experiences.

Learn more about how modals work in Bootstrap here.

You can toggle between multiple modals by strategically using the data-bs-target and data-bs-toggle attributes. Keep in mind that you can't have multiple modals open simultaneously—this method simply toggles between two separate modals.

Check out how to toggle between modals here.

Instead of stacking modals, use toggling for a better user experience without requiring any z-index manipulation tricks.

Your specific problem.

The reason why the modal closes when clicking the "Add File" button is due to...

<button data-bs-target="#modal-toggle2" data-bs-toggle="modal" class="btn btn-primary file-${code}">Add File Inside ${code}</button>

Your button's data-bs-target and -toggle create a new 'file', which triggers the opening of modal #modal-toggle2. Since this modal doesn't exist on your page, an error occurs due to an undefined modal.

You also have some typos, such as missing closing <div> tags in certain places.

Your solution...

  • Append the modal to the body instead of the <li> element.
  • Utilize the data attributes data-bs-target and data-bs-toggle to toggle the modals effectively.
  • Include a "Go back to folder" button when accessing the modals related to files.

// Your JavaScript code snippet goes here
// Remember to include relevant libraries and CSS files as needed

If you want the top-right close button (X) in the 'File' modal to behave like a back button to the 'folder' modal, you can simply add:

<button type="button" class="btn-close" data-bs-toggle="modal" data-bs-target="#modal-${code}" aria-label="Close"></button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using AngularJS to handle click events and blur events

I am attempting to dynamically change the class based on user interaction in my code. The class should switch between "large" and "active" depending on whether the input field is filled or not. Please see the modified script below. <div class="snippe ...

What is the best approach to synchronize checkboxes with boolean values in my data model?

I've spent hours searching through similar questions, but haven't found a solution that perfectly matches my issue. What I need is to have a checkbox automatically checked based on a true/false value in my data using data binding. While I can suc ...

Angularjs directive: independent scope and encapsulated elements

Why aren't the contained/child elements rendering when using an isolated scope? I suspect that the parent is not rendered yet. I tried adding a $timeout, but still no luck. If I remove the isolated scope by commenting out scope: {}, it works. How c ...

Versatile dataTable designed to seamlessly integrate with various data structures

My task is to develop an ajax dataTable that can handle a variety of data sources with different column names and data types. The challenge lies in the fact that I cannot predefine the column names or data types when coding the dataTable, as each data sour ...

Organize JSON objects by their keys using jQuery's .each() method

{ "staff": { "2010": [ { "first_name": "john", "last_name": "doe", }, { "first_name": "jane", "last_name": "doe", } ], "2012": [ ...

What is the best method for storing a model in a database?

Hello, I am currently attempting to save a model to the database. I am simply inputting the value of a title in order to save it, as my id is set to auto increment. However, I have encountered an issue where my attempts have been unsuccessful. Can someone ...

Is it possible to modify the stroke color of the progress circle in ng-zorro?

I am working on an Angular project where I aim to create a dashboard displaying various progress circles. Depending on the progress, I need to change the color of the line. Current appearance: https://i.sstatic.net/hR2zZ.png Desired appearance: https://i. ...

Animate in Angular using transform without requiring absolute positioning after the animation is completed

Attempting to incorporate some fancy animations into my project, but running into layout issues when using position: absolute for the animation with transform. export function SlideLeft() { return trigger('slideLeft', [ state('void&a ...

Google Maps displays grayscale overlays on the latest version update

Hello, I am facing a challenging issue with the Google Maps API. I have come across some similar threads discussing this problem, but unfortunately, they did not provide a solution that suits my specific case. Currently, I am working on an angular.js 1. ...

Use either lodash or a for loop to organize a group of JSON objects

Here is the array I am working with: [ { corequisite: "", curriculumYr: "2017-2018", programCode: "ET" majorCode: "AET", prerequisites: "GMRC 101||Math 101" semester: "1st Term", year: "1st Year", subjectCode : "ENG ...

Having numerous sections condensed into one cohesive page

Currently, I am working with backbone.js to develop a single-page application that takes inspiration from the functionality of trello.com. I am interested in learning how to display multiple pages on top of the original page and effectively structure the ...

Use jQuery's .each method to reiterate through only the initial 5 elements

Is there a way to loop through just the initial 5 elements using jQuery's each method? $(".kltat").each(function() { // Restrict this to only the first five elements of the .kltat class } ...

Problem with Fancybox in Internet Explorer

For a recent project, I needed to incorporate Fancybox with manual image call using a JSON list. The code snippet below illustrates how this can be done: $("#big_img a").click(function(e) { e.preventDefault(); jsonObj = []; var ac ...

Optimizing Angular for search engines: step-by-step guide

Regarding Angular SEO, I have a question about setting meta tags in the constructors of .ts files. I have implemented the following code: //To set the page title this.titleServ.setTitle("PAGE TITLE") //To set the meta description this.meta.addTag ...

Is there a way to automatically populate textbox values using a MySQL query response when the dropdown selection is changed?

How can I make the fields customer_address, customer_city, customer_state, and customer_zip autofill upon changing the selection in the dropdown for customer_name? I've searched everywhere but cannot find a solution. Your assistance would be greatly ...

What is the trick to getting the <label> and <input> elements to show up side by side in an HTML form?

I am designing a registration form for a new website. My goal is to have each label and its corresponding input element displayed on the same line. Here's the CSS code I'm using: #registration-form { background-color: #FFF; height: 600px; ...

The custom pagination feature on WordPress is not functioning as expected

I've been working on a WordPress project recently and I encountered an issue with the custom pagination I implemented. Everything works fine when navigating to pages 2, 3, etc., but when trying to go back to the first page by clicking on the '1&a ...

Selenium: Discrepancies between browser display and HTML code are evident

When attempting to log in to this page using Selenium and Python, I encountered a discrepancy between the page displayed in the browser and the one described in the HTML code. Both Firefox and Chrome webdrivers yielded the same result. chromedriver = "./c ...

Angular directive button failing to trigger ng-click event

Recently, I started working with Angular and ran into an issue while trying to set up a custom directive. The purpose of this directive is to display a button upon hovering over it, which, when clicked, should trigger a function within the directive. The b ...

Using Javascript or jQuery, focus on a div containing a paragraph element with a particular text

I've been struggling for hours trying to figure out how to select a div that contains a specific p element. HTML <div class="NavBar_Row_Button2"><p>DONATE</p></div> <div class="NavBar_Row_Button2"><p>CONTACT</p ...