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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With