jquery-ui-dialog - How to hook into dialog close event
Asked Answered
B

11

194

I am using the jquery-ui-dialog plugin

I am looking for way to refresh the page when in some circumstances when the dialog is closed.

Is there a way to capture a close event from the dialog?

I know I can run code when the close button is clicked but that doesn't cover the user closing with escape or the x in the top right corner.

Bolzano answered 5/10, 2008 at 12:52 Comment(0)
B
256

I have found it!

You can catch the close event using the following code:

 $('div#popup_content').on('dialogclose', function(event) {
     alert('closed');
 });

Obviously I can replace the alert with whatever I need to do.
Edit: As of Jquery 1.7, the bind() has become on()

Bolzano answered 5/10, 2008 at 13:42 Comment(7)
typo: $('div#popup_content').bind('dialogclose', function(event)) { ... }Moline
This is helpful but is $('div#popup_content') right? What should I be replacing this with, bearing in mind my dialog is opened like this jQuery.fn.dialog.open({})Hades
I see the dialog closes first and then the alert appears, if it is same situation to everyone, can someone help me so that alert appears first and then on click of OK then the window closes? Correct me....Indefinite
I keep getting "ReferenceError: event is not defined". How should I define event?Phytology
This should be updated to use on() instead of bind() which is now obsolete.Pliam
Keep in mind that if a jQuery UI Dialog has never been opened before on a page, then the overlay div won't exist in the DOM. Hence, you may consider doing something like this instead: $('body').on('dialogclose', '.ui-dialog', function(){...});Hexagram
In case it's useful to others, the event will have an eventPhase property when closed with the X icon or Esc key. If you close programmatically (e.g. $(...).dialog('close')) that won't be present. This is one way to differentiate.Murrelet
C
203

I believe you can also do it while creating the dialog (copied from a project I did):

dialog = $('#dialog').dialog({
    modal: true,
    autoOpen: false,
    width: 700,
    height: 500,
    minWidth: 700,
    minHeight: 500,
    position: ["center", 200],
    close: CloseFunction,
    overlay: {
        opacity: 0.5,
        background: "black"
    }
});

Note close: CloseFunction

Corsiglia answered 5/10, 2008 at 19:35 Comment(7)
This answer seems more correct to me than the accepted answer. Also, the correct API documentation can be found here: api.jqueryui.com/dialog/#event-closeCynewulf
Jake N - You need to actually write a function accessible to the dialog called 'CloseFunction' for this to work, for example just above you could write var CloseFunction = function() { //Do your custom closing stuff here };Instant
This is an option but at time the code is being used in different places. The selected answer works for when you want to add different behavior in different contexts and reuse the dialog creation code to get standardization.Duncandunce
You have overlay twice. That isn't nessesary right?Arwood
I suppose not...since the first would override the second. I've removed it.Corsiglia
This works and is definitely a needed and useful answer here, but it also runs the CloseFunction code any time the dialog is closed by any means, not just when closed with the X or something. So if you want to run certain code when the dialog is closed with the X or the Cancel button, but not when it's closed by something else happening (like in my case when a submitted input is validated as correct), then this won't work.Laudation
I ended up using a workaround to set a data item for my dialog, which is a boolean flag set elsewhere, and I use that to determine whether my close code as in this answer should execute or not. To be explicit, the first thing after my close: is an if conditional that checks the data item.Laudation
S
33
$("#dialog").dialog({
    autoOpen: false,
    resizable: false,
    width: 400,
    height: 140,
    modal: true, 
    buttons: {
        "SUBMIT": function() { 
        $("form").submit();
    }, 
        "CANCEL": function() { 
        $(this).dialog("close");
    } 
    },
    close: function() {
      alert('close');
    }
});
Sansbury answered 10/11, 2009 at 8:6 Comment(0)
C
22
$( "#dialogueForm" ).dialog({
              autoOpen: false,
              height: "auto",
              width: "auto",
              modal: true,
                my: "center",
                at: "center",
                of: window,
              close : function(){
                  // functionality goes here
              }  
              });

"close" property of dialog gives the close event for the same.

Comte answered 17/7, 2014 at 8:43 Comment(0)
C
16

U can also try this

$("#dialog").dialog({
            autoOpen: false,
            resizable: true,
            height: 400,
            width: 150,
            position: 'center',
            title: 'Term Sheet',
            beforeClose: function(event, ui) { 
               console.log('Event Fire');
            },
            modal: true,
            buttons: {
                "Submit": function () {
                    $(this).dialog("close");
                },
                "Cancel": function () {
                    $(this).dialog("close");
                }
            }
        });
Cobaltite answered 20/6, 2012 at 9:45 Comment(0)
A
10

This is what worked for me...

$('#dialog').live("dialogclose", function(){
   //code to run on dialog close
});
Amena answered 19/7, 2011 at 17:59 Comment(0)
C
8

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.

Because no one actually created an answer with using .on() instead of bind() i decided to create one.

$('div#dialog').on('dialogclose', function(event) {
     //custom logic fired after dialog is closed.  
});
Cluff answered 10/11, 2014 at 8:7 Comment(3)
The OP's answer is basically identicalNutty
@Nutty true. OP updated the answer to on() in 2015 :)Cluff
I wasn't aware they updated theirs after yours, I'll change my downvote to an upvote if you edit your answerNutty
D
6

add option 'close' like under sample and do what you want inline function

close: function(e){
    //do something
}
Drier answered 24/11, 2016 at 10:57 Comment(0)
S
4

If I'm understanding the type of window you're talking about, wouldn't $(window).unload() (for the dialog window) give you the hook you need?

(And if I misunderstood, and you're talking about a dialog box made via CSS rather than a pop-up browser window, then all the ways of closing that window are elements you could register click handers for.)

Edit: Ah, I see now you're talking about jquery-ui dialogs, which are made via CSS. You can hook the X which closes the window by registering a click handler for the element with the class ui-dialog-titlebar-close.

More useful, perhaps, is you tell you how to figure that out quickly. While displaying the dialog, just pop open FireBug and Inspect the elements that can close the window. You'll instantly see how they are defined and that gives you what you need to register the click handlers.

So to directly answer your question, I believe the answer is really "no" -- there's isn't a close event you can hook, but "yes" -- you can hook all the ways to close the dialog box fairly easily and get what you want.

Sill answered 5/10, 2008 at 13:12 Comment(1)
Hey andy. I amusing the the dialog from jquery-ui which is made via css and javascript. From looking at the code I think there's a hook in there for me but I don't know how to get to it.Bolzano
S
2

You may try the following code for capturing the closing event for any item : page, dialog etc.

$("#dialog").live('pagehide', function(event, ui) {
      $(this).hide();
});
Salsala answered 16/6, 2011 at 11:56 Comment(1)
Just use .on() -- instead of .live() or .bind()Phantom
L
0

In my case popup dialogue is called on a button click like this and I attach close button events with timeout:

DialogBoxShareDesign();
setTimeout(clsBtnFunc(),1000);

function clsBtnFunc() {
    $("[aria-describedby='dialog-loginregister'] .csdialog-cancel").click(function (el) {
        alert('close by cancel button');
    });

    $("[aria-describedby='dialog-loginregister'] .ui-dialog-titlebar-close").click(function (el) {
        alert('close by x button');
    });
}
Leukocyte answered 21/3 at 18:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.