Ra3IDeN Ra3IDeN - 3 months ago 13
jQuery Question

How to catch event when user clicks outside of bootstrap modal dialog?

Scenario:


  1. I click on a button

  2. Ajax call is made to the server

  3. data is returned and modal is shown



Problem:

When user clicks on the close button or the "X" in the corner I catch this event by assigning a class to these two elements and assigning an event to this class.

Code:

$(document).on("click", ".dialogTankClose", function() {
//some code
})


My problem is that i can't figure out how to catch when the user clicks outside of the dialog or presses "escape".

$(document).on("click", "modalCloseEvent",function(){
// how to catch this?
})


How can I catch this?

Answer

The Bootstrap modal raises an event when it closes, which you can hook to: hidden.bs.modal. This event fires no matter how the modal is closed. Try this:

$('#bootstrapModal').on("hidden.bs.modal", function() {
    $.automation.worker.bindIntervalEvent("#TanksContent", "/Tank/GetTanks", function () {
        $.automation.tanks.tableInit();
    });
});

You can use a delegated event handler if the modal is dynamically added to the DOM:

$(document).on("hidden.bs.modal", '#bootstrapModal', function() {
    $.automation.worker.bindIntervalEvent("#TanksContent", "/Tank/GetTanks", function () {
        $.automation.tanks.tableInit();
    });
});

More information in the Bootstrap documentation