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?

Salman A
  • 262,204
  • 82
  • 430
  • 521
user208662
  • 10,869
  • 26
  • 73
  • 86

5 Answers5

181

If you read the docs.

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

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

Salman A
  • 262,204
  • 82
  • 430
  • 521
Byron Whitlock
  • 52,691
  • 28
  • 123
  • 168
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
}
Timo Tijhof
  • 10,032
  • 6
  • 34
  • 48
marcovtwout
  • 5,230
  • 4
  • 36
  • 45
  • 4
    Returns false in the latest JQuery. – hoyhoy Apr 20 '12 at 21:48
  • 1
    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? – Kirk Ross Nov 12 '14 at 21:56
  • 2
    Maybe create a function like $(".ui-dialog").each(function(/*check this dialog*/))? – marcovtwout Nov 13 '14 at 08:41
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
}
Timo Tijhof
  • 10,032
  • 6
  • 34
  • 48
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
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; }
user2452922
  • 153
  • 1
  • 8
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

bnieland
  • 6,047
  • 4
  • 40
  • 66
Avinash
  • 21
  • 1