How to check, if any bootstrap modal is currently open?
The reason behind: I want to deactivate certain keyhandler, if a modal is open.
If you are using jquery, you can use this :
function isABootstrapModalOpen() {
return $('.modal.in').length > 0;
}
Vanilla JS solution :
function isABootstrapModalOpen() {
return document.querySelectorAll('.modal.in').length > 0;
}
This solution works for any modal, not just a specific one.
Edit: the code above test if, at any given moment, a modal is open. As indicated in the other answers, if you want to disable an event handler the moment the modal is opened, you'll have to use the bootstrap events, like this :
// when any modal is opening
$('.modal').on('show.bs.modal', function (e) {
// disable your handler
})
// when any modal is closing
$('.modal').on('hide.bs.modal', function (e) {
// enable your handler
})
You can also use isABootstrapModalOpen in your event handler, to test if the handler's code has to be executed (so you don't to enable/disable the handler each time a modal is opened/closed).
function eventHandler(e) {
// if a modal is open
if(isABootstrapModalOpen()) {
// prevent the event default action
e.preventDefault();
// and exit the function now
return;
}
// if a modal is not open
// proceed to the rest of the handler's code
}
The Bootstrap modals fire events when opened. In your case, I'd suggest to bind an event to the show.bs.modal
event and unbind your key handler event. Simple example:
$('#myModal').on('show.bs.modal', function (e) {
// yadda yadda .unbind()
})
Docs: http://getbootstrap.com/javascript/#modals, scroll down to Events.
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