A Bootstrap Modal is used to show important information to site’s visitors. This can be some sort of confirmation (like cookies information, updating or deleting profile), session time out or a new product launch. You will also find that these Bootstrap Modals are used by website owners to collect email addresses for newsletter subscription.
Modals are made even more powerful in Bootstrap 4. They are very easy to create and shows up on the top of your web page. Thes modal can be triggered by a link, button click or by a JavaScript code. They are also responsive so they automatically adapts themselves to every screen size.
Below is the HTML code of the Bootstrap Modal which you can place in any of your web page.
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" 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">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Explanation
Trigger Part: My Bootstrap Modal’s id is myModal and it can be triggered by using a button or a link that should have the following 2 attributes.
The modal-dialog class is used to provide width and margin to the modal.
The modal-header class forms the header of the modal. It contains a button with attribute data-bs-dismiss=”modal”, on clicking it the modal closes.
The modal-title class is the place where you can provide the title for the Bootstrap Modal.
Similarly, modal-body is the body of the modal. Provide your contents here.
The modal-footer is the modal footer that contains a Close button.
It is not necessary to show Bootstrap Modal by Button or Link click, in fact you can call the .modal(“show”) method though JavaScript code to show the modal.
The below JavaScript code will show the modal whenever the page is loaded.
<script>
$(document).ready(function () {
$("#myModal").modal("show");
});
</script>
You can also change the size of Bootstrap modal to a smaller or larger one. For doing this you need to add a class to class=”modal-dialog”>.
For small Bootstrap modal add modal-sm class with the modal-dialog.
<div class="modal-dialog modal-sm">
For large Bootstrap modal add modal-lg class with the modal-dialog.
<div class="modal-dialog modal-lg">