Dedicated event handler for close (x) button in jQuery UI Dialog

javascript, jquery, jquery-ui, jquery-ui-dialog

Solution

Whenever one event leads to another event inside a jQuery UI widget, the original event is always included in the event object. In this case, you can look at the event object passed to the `close` callback or the `dialogclose` event and check if `event.originalEvent` exists. If it does, then you can assume that the dialog was closed via a click on the close button. This also applies to `beforeclose`.

If you want to be absolutely sure that it was the close button in the titlebar, then you can check `event.originalEvent.target` and either check the class or the DOM location using `.closest()`.

Here's a jsbin showing this in action: http://jsbin.com/ajoheWAB/1/edit

Problem

Is there a way to wire into the close (x) button on a jQuery UI Dialog, such that you can provide a dedicated event handler? Using the "close" or "beforeclose" event does not work because if you have other buttons in your dialog that also cause the dialog to close, you are always going to hit the "close" and "beforeclose" events, which is not desirable. I want a way to run specific code from the close (x) button.

Original source