Search code examples
javascriptjqueryjquery-uijquery-ui-dialog

Checking if dialog isOpen throws "cannot call methods on dialog prior to initialization" error


I'm using a dialog and checking it with the code that i found in the docs

var isOpen = $( "#dialogName" ).dialog( "isOpen" );
$("#here").on("click", function(e){
    if(isOpen){
        $("#dialogName").dialog("close");
    } 
});

Sometimes I get the error:

Uncaught Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

And sometimes that it can't find isOpen. What i want to do is:

On click #here it must check if the dialog is alive then close otherwise do nothing.


Solution

  • isOpen is a method called on an existing dialog, while the dialog has not been yet initialized.

    You should initialize the dialog first, then inside click event handler check whether the dialog isOpen currently.

    // initialize the dialog:
    var myDialog = $( "#dialogName" ).dialog({
        // dialog settings:
        autoOpen : false,
        // ... 
    });
    
    $("#here").on("click", function(e){
        // on click, check if is opened:
        var isOpen = myDialog.dialog("isOpen");
        if(isOpen){
           myDialog.dialog("close");
        } 
    });
    

    DEMO