greenhoorn
greenhoorn

Reputation: 1561

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.

Upvotes: 8

Views: 21033

Answers (4)

Tran Van Hieu
Tran Van Hieu

Reputation: 131

Update 2024 Bootstrap 5 with React

we can use useEffect for listen close, open modal event

  useEffect(() => {
    document
      .getElementById("login-modal")
      .addEventListener("hidden.bs.modal", function (event) {
        console.log("close ok");
      });
  }, []);

Upvotes: 0

Rohan Kumar
Rohan Kumar

Reputation: 40639

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

Upvotes: 21

Andrew Koster
Andrew Koster

Reputation: 1835

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/

Upvotes: 1

Novocaine
Novocaine

Reputation: 4786

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.

Upvotes: 12

Related Questions