
Bootstrap 5 Modal is a popup box or window that appears on the screen. It contains text, images, buttons, forms, and any other type of content. You can use the Bootstrap modal to show any message or data in a popup dialog box.
This tutorial will show you how to create nested Bootstrap 5 modal windows by using JavaScript. The nested modal can be opened by clicking on any button placed inside the parent modal.
How to use it:
1. Load the necessary Bootstrap 5 framework.
<link rel="stylesheet" href="/path/to/cdn/bootstrap.min.css" /> <script src="/path/to/cdn/bootstrap.bundle.min.js"></script>
2. Insert a modal trigger button into the parent modal as follows:
<!-- Main Modal --> <div class="modal" id="myModal" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <button type="button" class="btn btn-primary showmodal" data-show-modal="infoModal"> Show Second Modal </button> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div>
3. Create the second nested modal on the page.
<!-- Second nested Modal --> <div class="modal mt-5 ms-5" id="infoModal" tabindex="-1" aria-labelledby="infoModalLabel" aria-hidden="true" data-bs-backdrop="static"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="infoModalLabel">Modal Title</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <p>The Second Modal</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div>
4. Add the following JS snippets into your document. That’s it.
Array.from(document.getElementsByClassName('showmodal')).forEach( (e) => { e.addEventListener('click', function(element) { element.preventDefault(); if (e.hasAttribute('data-show-modal')) { showModal(e.getAttribute('data-show-modal')); } }); }); // Show modal dialog function showModal(modal) { const mid = document.getElementById(modal); let myModal = new bootstrap.Modal(mid); myModal.show(); }
Changelog:
05/12/2022
- Fix backdrop z-index for each modal
The post Create Nested Bootstrap 5 Modal With JavaScript appeared first on CSS Script.