Check if any boot modal is open

How to check if any bootable modal is currently open ?

Reason: I want to deactivate a specific manipulator if the modal is open.

+4
source share
5 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 specific.

Edit : the code above the test, if at any time the modal is open. As indicated in other answers, if you want to disable the event handler at the moment the modality is opened, you will have to use boot events, for example:

// 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
})

isABootstrapModalOpen , , ( / / ).

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 code 
}
+9

Bootstrap . show.bs.modal . :

$('#myModal').on('show.bs.modal', function (e) {
    // yadda yadda .unbind()
})

: http://getbootstrap.com/javascript/#modals, .

+1

:

$(document).find('.modal').each(function(e) {

    var element = $(this);

    if ( (element.data('bs.modal') || {isShown: false}).isShown ) {
      console.log('a modal is open');
    }

});
+1

:

alert($('#myModal').hasClass('in'));
0

jQueries hasClass.

return $('div.modal).hasClass('in'); // True if open, false if closed
0

All Articles