Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap modal event not fired

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.

like image 677
greenhoorn Avatar asked Feb 12 '15 08:02

greenhoorn


3 Answers

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

like image 159
Rohan Kumar Avatar answered Nov 06 '22 16:11

Rohan Kumar


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.

like image 44
Novocaine Avatar answered Nov 06 '22 18:11

Novocaine


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/

like image 1
Andrew Koster Avatar answered Nov 06 '22 17:11

Andrew Koster