How to close a jQuery dialog box by clicking outside of it
Posted: November 30, 2009
JQuery gives you a very simple way to create dialog overlays with the dialog() event. So, by clicking an HTML element you can activate a “stay-on-the-page” overlay dialog box.
Traditionally one might use dialog boxes to ask the user a question to which she must respond (e.g. with an “Ok” or “Cancel”) but their use can extend beyond this. For instance I’ve used a dialog to show a mega drop-down menu; i.e. clicking a link opens a dialog box with a list of categorised links.
JQuery’s default behaviour for closing dialog boxes is not unreasonable: the user must click on the “Close” button (e.g. in the form of text or an “x”) or hit the escape key. However it’s possible you may want to provide more options for your users to close a box by simply clicking outside it.
I puzzled over this and didn’t get very far with Googling but came up with the following solution which seems to work.
When your dialog is created, a div with the class “ui-widget-overlay” is also created which “greys out” the background allowing the user to fully focus on the dialog. You can use this as a hook to add your dialog closing code, e.g.
$(".ui-widget-overlay").live("click", function() { $("#quick-links-modal").dialog("close"); } );
In this case my dialog has the ID “quick-links-modal”. NB you need to use the “live” event (rather than “click” etc.) in order to bind the event to your dialog before the dialog has been initiated.
No comments? The comments haven't exactly been coming thick and fast recently so I've disabled them for the time being. Instead, why not drop me a Tweet at @littlednet or email me at info@littled.net?