How can I open a second modal on top of a first without scroll issues?
Asked on Jun 26, 2025
1 Answer
In Bootstrap 5, you can open a second modal on top of the first by ensuring that the body's scroll position is maintained. This can be achieved by using JavaScript to handle the modals' z-index and scroll behavior.
<!-- BEGIN COPY / PASTE -->
<!-- First Modal -->
<div class="modal fade" id="firstModal" tabindex="-1" aria-labelledby="firstModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="firstModalLabel">First Modal</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
Content for the first modal.
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#secondModal">Open Second Modal</button>
</div>
</div>
</div>
</div>
<!-- Second Modal -->
<div class="modal fade" id="secondModal" tabindex="-1" aria-labelledby="secondModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="secondModalLabel">Second Modal</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
Content for the second modal.
</div>
</div>
</div>
</div>
<script>
// Ensure body scroll is managed correctly
var firstModal = document.getElementById('firstModal');
var secondModal = document.getElementById('secondModal');
firstModal.addEventListener('hidden.bs.modal', function () {
if (secondModal.classList.contains('show')) {
document.body.classList.add('modal-open');
}
});
</script>
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with Bootstrap 5 best practices.- Ensure both modals have unique IDs and aria-labelledby attributes.
- The second modal is triggered from within the first modal using a button with data-bs-toggle and data-bs-target attributes.
- JavaScript listens for the 'hidden.bs.modal' event on the first modal to reapply the 'modal-open' class if the second modal is still open.
- This prevents the body from scrolling when the first modal is closed while the second is still open.