I have a page where one Bootstrap modal opens another modal.
The problem is that with each opened modal, it adds
<div class="modal-backdrop fade in"></div>
to the HTML code. It's fine for the first one, but since it's opacity: .5;
it then makes the page darker on every modal opened. Is there a way to check if a modal-backdrop
already exists and in that case not open another one?
I open my modals with either
<a href="" data-target="#modal_01" data-toggle="modal">Modal</a>
or with jQuery:
$('#modal_01').modal('show');
Any help to this problem is greatly appreciated!
Here's a fiddle for your convenience: https://jsfiddle.net/zsk4econ/1/
It is possible for multiple modals to contain more than two modals (hence our usage of the name multiple modals rather than the term double modals that many sources use).
You can toggle between modals by having putting data-dismiss="modal" and data-toggle="modal" in the same HTML element.
Here is the working demo that I think will fit in your case.
$(".modal").on("shown.bs.modal", function () {
if ($(".modal-backdrop").length > 1) {
$(".modal-backdrop").not(':first').remove();
}
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-body">
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal2">Open Modal</button>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal2" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-body">
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal3">Open Modal 3</button>
</div>
</div>
</div>
</div>
</div>
Let CSS handle it.
.modal-backdrop:nth-child(2n-1) {
opacity : 0;
}
https://jsfiddle.net/zsk4econ/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With