22

What is the difference between .dialog("close") and .dialog("destroy") in jquery-ui?

I have a script where the previous developer had used .dialog("destroy") but now I've to perform some actions once the dialog is closed. I've found beforeclose that is called with .dialog("close") and not with .dialog("destroy"). So I've to change the method from destroy to close to make it work.

So is there anything that I'll miss if I use .dialog("close") and not .dialog("destroy") ?

PS: The dialog is using custom buttons to close itself, and the .dialog("close") is called on the click event of the button

2

3 Answers 3

31

close leaves the dialog configured, but invisible, so you can reopen it again with .dialog('open').

destroy will completely deconfigure the dialog box. It'll remove all of the UI elements that were added to the DOM, and any related event handlers.

destroy will not remove the element that held the contents of the dialog box (i.e. the element that you call .dialog on)

1
  • I saw a peculiar behavior today. I had two dialogs open, each with separate DIVs and Forms and Fieldsets. When I 'closed' the second one to open, it cleared all the values from the first dialog's input fields! When I 'destroyed' the second one instead, the first dialog was left alone. Since I rebuild the dialog each time, it was not an issue. Commented Mar 31, 2022 at 23:31
8

Remember if you are using the dialog for forms input, that destroying it will NOT remove your input, so if you are validating with the :input pseudo selector, the elements you 'destroyed' will be validated. This is where .remove() comes in handy.

You can add a custom close event that destroys your dialog and removes any form inside it to prevent further validation of it.

$dialog = $("#your_dialog_id");
$dialog.dialog('option', {
    title: "title",
    close: function (event, ui) {
        $dialog.find("form").remove();
        $dialog.dialog('destroy');
    }
});
6

From Docs:

destroy:

Removes the dialog functionality completely. This will return the element back to its pre-init state.

close:

Closes the dialog, which can re-opened when needed.

Not the answer you're looking for? Browse other questions tagged or ask your own question.