You can close a modal programmatically using JavaScript in Bootstrap. Following are the steps:
1. Use the Bootstrap’s Modal Method
You need to use the .modal(‘hide’) method to close the modal popup.
Example:
$('#myModal').modal('hide');
2. Use the DOM API (hide method)
var modalElement = document.getElementById('myModal'); var modal = bootstrap.Modal.getInstance(modalElement); modal.hide();
3. Automatically Closing via Data Attributes
You can close or hide a modal by including a button or link with the <code>data-bs-dismiss=”modal”</code> attribute inside the modal of bootstrap:
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
4. Closing a Modal on a Custom Trigger
If you want to close or hide the modal on a custom event , you can trigger the above methods in your JavaScript:
document.getElementById('submitBtn').addEventListener('click', function() { var modalElement = document.getElementById('myModal'); var modal = bootstrap.Modal.getInstance(modalElement); modal.hide(); });
<h3>Full Example</h3>
<b>HTML</b>
<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 of Example</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> Modal content here... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close this modal</button> <button type="button" id="submitBtn" class="btn btn-primary">Submit Form</button> </div> </div> </div> </div>
<b>JavaScript</b>
document.getElementById('submitBtn').addEventListener('click', function() { var modalElement = document.getElementById('myModal'); var modal = bootstrap.Modal.getInstance(modalElement); modal.hide(); });
This ensures the modal closes programmatically as needed.