Detect if a jQuery UI dialog box is open
Asked Answered
M

5

100

I am using a jQuery UI dialog. If it is open, I want to do one thing. If it is closed, I want to do another.

My question is, how do I detect if a jQuery UI dialog box is open or not?

Matriculate answered 22/7, 2010 at 21:48 Comment(0)
M
182

If you read the docs.

$('#mydialog').dialog('isOpen')

This method returns a Boolean (true or false), not a jQuery object.

Multidisciplinary answered 22/7, 2010 at 21:51 Comment(5)
How would you do this test for any and all dialogs? Say you have ten different dialogs with separate inits and options and you want to test if ANY of them are open, not a specific selector?Bib
Add a class to said dialogs, then change the selector on your isOpen check.Microphone
plus also: ten dialogs? maybe reducing that by re-using an instance or two is a thought worth consideringIntra
Also check if dialogue has even been initialized with $("#mydialog").hasClass("ui-dialog-content"). See #29529206Studnia
it returns the objectMagnificence
F
56

Actually, you have to explicitly compare it to true. If the dialog doesn't exist yet, it will not return false (as you would expect), it will return a DOM object.

if ($('#mydialog').dialog('isOpen') === true) {
    // true
} else {
    // false
}
Flagging answered 18/11, 2011 at 11:24 Comment(3)
Returns false in the latest JQuery.Topknot
How would you do this test for any and all dialogs? Say you have ten different dialogs with separate inits and options and you want to test if ANY of them are open, not a specific selector?Bib
Maybe create a function like $(".ui-dialog").each(function(/*check this dialog*/))?Flagging
F
22

If you want to check if the dialog's open on a particular element you can do this:

if ($('#elem').closest('.ui-dialog').is(':visible')) { 
  // do something
}

Or if you just want to check if the element itself is visible you can do:

if ($('#elem').is(':visible')) { 
  // do something
}

Or...

if ($('#elem:visible').length) { 
  // do something
}
Farceur answered 22/7, 2010 at 21:50 Comment(2)
I check my div if it not initialized like that: $dialog.hasClass('ui-dialog-content')Hofstetter
Thanks, I couldn't get the above answers using "isOpen" to work for me, but this worked.Imbroglio
N
3

Nick Craver's comment is the simplest to avoid the error that occurs if the dialog has not yet been defined:

if ($('#elem').is(':visible')) { 
  // do something
}

You should set visibility in your CSS first though, using simply:

#elem { display: none; }
Newfangled answered 29/12, 2017 at 16:33 Comment(0)
V
2

jQuery dialog has an isOpen property that can be used to check if a jQuery dialog is open or not.

You can see example at this link: http://www.codegateway.com/2012/02/detect-if-jquery-dialog-box-is-open.html

Vito answered 26/2, 2012 at 7:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.