Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twitter bootstrap modal hidden event only fires once

I'm using a page with a single modal defined on it ("#agenda-modal"). When a trigger (.agenda-item) is clicked, I'm showing this modal with remote content like so:

$("body").on("click", ".agenda-question", function(e){
  var url = <build my url here>;
  $("#agenda-modal").modal({
    remote: url
  });
});

This works fine (I'm using listening to $body.on because .agenda-items are added via javascript).

When the modal is closed, I want to reload a part of the page (the part that the form inside the modal modifies). So I'm using:

$("#agenda-modal").on("hidden", function(){
  alert("hidden");
});

Of course, all wrapped up in

$(function() {...});

This works, but only once! When I first load the page and click a trigger, the modal loads up & when I close the modal the alert happens. If I click the same trigger again, the modal shows up again but this time when it closes the alert does not happen!

I don't know, but is this because the listener - on("hidden", function...) - is not "bound" anymore? I thought .on will always catch the event?

The code for the modal is straight off twitter:

<div class="modal hide fade" id="agenda-modal">
  <div class="modal-body"></div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal">Close</button>
  </div>
</div>

Any ideas? I really want to catch when a modal closes so that I can update the part of the page that would have been changed.

Using rails btw, not sure if that matters...

like image 302
user2563682 Avatar asked Jul 22 '13 13:07

user2563682


2 Answers

change

$("#agenda-modal").on("hidden", function() {
  alert("hidden");
});

to

$(document).on('hidden.bs.modal', '#agenda-modal', function () {    
  alert("hidden");
});
like image 189
v.liukh Avatar answered Nov 07 '22 01:11

v.liukh


This is a known issue with Bootstrap

The issue is the event needs to be re-added every time it is fired, but on a delay.

Here is an example:

function hiddenModal() {
    alert("hidden");
    setTimeout(function() {
        $("#agenda-modal").on("hidden", hiddenModal );
    }, 222);
}

$("#agenda-modal").on("hidden", hiddenModal );

This is similar to another question, but for a different kind of event:

  • Radio buttons change() event only firing once when using $().button('reset')
like image 23
digitalextremist Avatar answered Nov 07 '22 01:11

digitalextremist