Opening and closing a Bootstrap modal using the traditional button method and then with jQuery targeting with a button click.
Traditional way
Opening (showing) the modal the traditional way with data-toggle and data-target
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#theModal">Open</button>
Closing (hiding) the modal with data-dismiss
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
With jQuery
Or you can create buttons with a click function to show
the modal or hide
the modal.
<button type="button" class="btn btn-success" id="modalOpen">Open</button> <button type="button" class="btn btn-warning" id="modalClose">Close</button>
On document ready wait for the button clicks:
$(document).ready(function () { $("#modalOpen").click(function () { $('#theModal').modal('show'); }); $("#modalClose").click(function () { $('#theModal').modal('hide'); }); });
toggle
can also be used, this will show if hidden and hide if shown. However, using this method means you don’t always know or have control of what state the modal is in.
Check if modal is shown
A method to check if a modal is active (shown) or not:
if ($("#theModal").hasClass("show")) { alert('is shown'); }
This checks if the modal has the class show
.