简体   繁体   中英

How to open/close a bootstrap modal without triggering event?

I have a bootstrap modal that trigger additional actions when opened or closed manually. These actions are hooked with show.bs.modal and hide.bs.modal events.

Now I want to also be able to open or close modal programmatically without triggering this action. Is it possible?

You need a way of determining how the modal was triggered; a flag or similar.

According to the Bootstrap documentation (assuming you're using version 3), e.relatedTarget is set as the element which was clicked for the show.bs.modal event in your callback. Thus, e.relatedTarget is undefined if triggered programmatically. You can use this to avoid your show.bs.modal callback function from running. For example:

$('#myModal').on('show.bs.modal', function (e) {
  if (e.relatedTarget) {
    // User triggered, do something...
  }
});

As for the hide.bs.modal event, there isn't a similar attribute available, but you could achieve the same effect with a toggle class or data attribute. Set this flag just before you're about to hide your modal in your code, and ensure that your modal's hide.bs.modal callback is checking for its presence, and only run if not present. For example:

// Prep modal event
$('#myModal').on('hide.bs.modal', function (e) {
    if (!$('#myModal').hasClass('programmatic')) {
        // User triggered, do something...
    }
});

// When hiding your modal
$('#myModal').toggleClass('programmatic');
$('#myModal').modal('hide');

For both of the above cases, another option is to remove your event listener before showing/hiding, trigger the modal to be shown/hidden, and re-add the event listener.

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