This post will specifically explain the procedure to close a Bootstrap Modal Window using jQuery.
How to Use jQuery to Close a Bootstrap Modal Window?
We will elaborate on the mentioned topic by covering the following steps:
Step 1: Create Bootstrap Modal Window in HTML
By using the Bootstrap modal classes, the modal window can be created efficiently:
- First, create a button element that will trigger the modal in Bootstrap by using the data attributes “data-toggle” and “data-target”.
- Then, make the modal window using the class “modal” and “fade”.
- The “modal-dialog”, “modal-content”, “modal-header”, “modal-title”, “modal-body”, and “modal-footer” are the classes that are implemented in the below-mentioned code to establish a flexible modal dialogue box:
<button type="button" class="btn btn-primary " data-toggle="modal" data-target="#welcomeModal">Launch Modal</button>
<div id="welcomeModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<p>Welcome to Linuxhint!</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" id="close-modal">Close</button>
<button type="button" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</div>
Step 2: Close the Bootstrap Modal Window Using jQuery
Generally, the data attribute “data-dismiss” with the value “modal” is specified to close the modal dialogue box. This attribute is applied to the button element to close the window.
In our scenario, we are interested in implementing jQuery to close the popup window. So, let’s discuss it with the help of implementation:
- Firstly, include the “<script>” tag in HTML.
- Specify the $() function that returns the id of the element. Associate it with the click event and connect it with the function that will invoke on click.
- Inside the function, mention the code “$(‘#welcomeModal’).modal(‘hide’)” that signifies that the id “welcomeModal” is going to be hidden by utilizing the “modal(‘hide’)” function:
$('#close-modal').on('click', function () {
$('#welcomeModal').modal('hide');
})
</script>
Output
In this way, you can close a Bootstrap Modal Window using jQuery.
Conclusion
To close a Bootstrap modal window by utilizing jQuery, create a modal window using the Bootstrap classes. Implement the jQuery function “$()” to get the id of the element and then associate the “modal(‘hide’)” function with it. This write-up has illustrated how to implement jQuery to close a Bootstrap modal window.