简体   繁体   中英

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?

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

You can use 'hidden.bs.modal' modal method to run custom code while modal is getting unload / hide from document.

$('#your-modal-ID').on('hidden.bs.modal', function (e) {
  console.log("Hey !! I am unloading... ");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM