Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if any bootstrap modal is open

How to check, if any bootstrap modal is currently open?

The reason behind: I want to deactivate certain keyhandler, if a modal is open.

like image 669
Razer Avatar asked Aug 30 '14 12:08

Razer


2 Answers

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 
}
like image 64
kerwan Avatar answered Sep 20 '22 15:09

kerwan


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.

like image 31
Bjorn Avatar answered Sep 20 '22 15:09

Bjorn