Can I check if Bootstrap Modal Shown / Hidden?

120,108

Solution 1

The best method is given in the docs

$('#myModal').on('shown.bs.modal', function () {
  // will only come inside after the modal is shown
});

for more info refer http://getbootstrap.com/javascript/#modals

Solution 2

its an old question but anyway heres something i used incase someone was looking for the same thing

if (!$('#myModal').is(':visible')) {
    // if modal is not shown/visible then do something
}

Solution 3

All Bootstrap versions:

var isShown = $('.modal').hasClass('in') || $('.modal').hasClass('show')

To just close it independent of state and version:

$('.modal button.close').click()

more info

Bootstrap 3 and before

var isShown = $('.modal').hasClass('in')

Bootstrap 4

var isShown = $('.modal').hasClass('show')

Solution 4

When modal hide? we check like this :

$('.yourmodal').on('hidden.bs.modal', function () {
    // do something here
})

Solution 5

Use hasClass('in'). It will return true if modal is in OPEN state.

E.g:

if($('.modal').hasClass('in')){
   //Do something here
}
Share:
120,108
user2736812
Author by

user2736812

Updated on July 11, 2022

Comments

  • user2736812
    user2736812 almost 2 years

    Can I check if Bootstrap Modal currently Shown / Hidden Programatically?

    Like bool a = if("#myModal").shown(); ?

    I need true/false

  • Mike Rapadas
    Mike Rapadas about 9 years
    This just reads so nicely. Also not dependent on specific class selectors which could prove fragile.
  • Dinei
    Dinei almost 9 years
    However, I believe it could return a false positive if it's executed during the showing/hiding animation.
  • ctf0
    ctf0 almost 9 years
    maybe but even though the function waits till the animation is finished to check if its visible or hidden as this one works the same as using normal css.
  • kiw
    kiw over 5 years
    this is what I was after, it already returns true while the modal is opening, but before the shown class is applied
  • DHW
    DHW about 4 years
    Sure, that's the best method for executing a function when the modal appears, but that's different from checking if it's currently shown or hidden, as OP asked. My use-case, for example, is to perform an action on keypress, but only if a certain class of modal is visible. I don't see how this method can be used for that.
  • Anther
    Anther about 4 years
    @DHW Couldn't you keep track of whether it's open or closed with those methods? If shown -> store that it's shown, when hidden -> store that it's hidden. Then you can just reference the relevant variables.