I want to simply do some logic after my modal has been dismissed.
In the modal I have a button:
<button type="button" class="btn btn-primary" onclick="$('#mymodal').modal('hide');">Save changes</button>
In the view I'm waiting for the event being fired, but it never does.
$('#mymodal').on('hide.bs.modal', function (e) {
alert('event fired')
});
I tried to put breakpoints in chrome dev tools, the event is only hit at the first load of the view. After that the breakpoint is never reached again. Am I doing something wrong?
By the way, the modal is hiding the way I want.
In your view you need to add dom ready function and write your code in it like,
$(function(){ // let all dom elements are loaded
$('#mymodal').on('hide.bs.modal', function (e) {
alert('event fired')
});
});
Working Demo
While the accepted answer is correct, I had a slightly different scenario which I didn't find an answer to.
I'm creating my modal's dynamically, so they don't exist on the page load. I'm adding them to the DOM with a JQuery .append('body')
. Therefore
$('#mymodal').on('hide.bs.modal', function(e) {
doesn't work....I had to change my event listener to
$(document).on('hide.bs.modal', '#mymodal', function(e) {
to work. Hopefully this will help others in the same situation as me.
Make sure that you actually have the Bootstrap Javascript library included in your page. That was my issue. The Bootstrap docs hint at this, but they omit it from the code examples.
Here are the files/CDNs for it, since their site avoids linking it from most of the relevant pages, for some reason: https://getbootstrap.com/docs/4.1/getting-started/download/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With