I would like to call some jQuery or javascript function on opening and closing Bootstrap pop-up modal in my project, So how can i do it, Suppose below is the code for Bootstrap pop-up modal.
<!-- 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-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Thanks.
For Calling jQuery function on specific modal show/hide using it's ID
//call function on modal shown
$('#myModal').on('shown.bs.modal', function (e) {
// do something...
});
//call function on hiding modal
$('#myModal').on('hidden.bs.modal', function (e) {
// do something...
})
if you want to call a function on show/hide on every modal of the page, using
$(window)
, instead of modal ID
//call function on modal shown
$(window).on('shown.bs.modal', function (e) {
// do something...
});
//call function on hiding modal
$(window).on('hidden.bs.modal', function (e) {
// do something...
})
that's it.
hidden.bs.modal
: event is fired when the modal has finished being hidden from the user .
shown.bs.modal
: event is fired when the modal has been made visible to the user.
When pop-up modal is open, you can call 'shown
' event, works in Bootstrap 5 also:
var myModal = document.getElementById('myModal')
var myInput = document.getElementById('myInput')
myModal.addEventListener('shown.bs.modal', function () {
myInput.focus()
})
For closed, you you can call 'hidden'
var myModalEl = document.getElementById('myModal')
myModalEl.addEventListener('hidden.bs.modal', function (event) {
// do something...
})
hidden.bs.modal
: This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete).
shown.bs.modal
: This event is fired when the modal has been made visible to the user (will wait for CSS transitions to complete). If caused by a click, the clicked element is available as the relatedTarget property of the event.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly