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
}
Author by
user2736812
Updated on July 11, 2022Comments
-
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 about 9 yearsThis just reads so nicely. Also not dependent on specific class selectors which could prove fragile.
-
Dinei almost 9 yearsHowever, I believe it could return a false positive if it's executed during the showing/hiding animation.
-
ctf0 almost 9 yearsmaybe 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 over 5 yearsthis is what I was after, it already returns
true
while the modal is opening, but before theshown
class is applied -
DHW about 4 yearsSure, 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 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.