I have a jQuery UI Dialog that gets displayed when specific elements are clicked. I would like to close the dialog if a click occurs anywhere other than on those triggering elements or the dialog itself.
Here's the code for opening the dialog:
$(document).ready(function() {
var $field_hint = $('<div></div>')
.dialog({
autoOpen: false,
minHeight: 50,
resizable: false,
width: 375
});
$('.hint').click(function() {
var $hint = $(this);
$field_hint.html($hint.html());
$field_hint.dialog('option', 'position', [162, $hint.offset().top + 25]);
$field_hint.dialog('option', 'title', $hint.siblings('label').html());
$field_hint.dialog('open');
});
/*$(document).click(function() {
$field_hint.dialog('close');
});*/
});
If I uncomment the last part, the dialog never opens. I assume it's because the same click that opens the dialog is closing it again.
Final Working Code
Note: This is using the jQuery outside events plugin
$(document).ready(function() {
// dialog element to .hint
var $field_hint = $('<div></div>')
.dialog({
autoOpen: false,
minHeight: 0,
resizable: false,
width: 376
})
.bind('clickoutside', function(e) {
$target = $(e.target);
if (!$target.filter('.hint').length
&& !$target.filter('.hintclickicon').length) {
$field_hint.dialog('close');
}
});
// attach dialog element to .hint elements
$('.hint').click(function() {
var $hint = $(this);
$field_hint.html('<div style="max-height: 300px;">' + $hint.html() + '</div>');
$field_hint.dialog('option', 'position', [$hint.offset().left - 384, $hint.offset().top + 24 - $(document).scrollTop()]);
$field_hint.dialog('option', 'title', $hint.siblings('label').html());
$field_hint.dialog('open');
});
// trigger .hint dialog with an anchor tag referencing the form element
$('.hintclickicon').click(function(e) {
e.preventDefault();
$($(this).get(0).hash + ' .hint').trigger('click');
});
});
The given example(s) use one dialog with id '#dialog', i needed a solution that close any dialog:
Thanks to my colleague Youri Arkesteijn for the suggestion of using prototype.
I use this solution based in one posted here:
For those you are interested I've created a generic plugin that enables to close a dialog when clicking outside of it whether it a modal or non-modal dialog. It supports one or multiple dialogs on the same page.
More information here: http://www.coheractio.com/blog/closing-jquery-ui-dialog-widget-when-clicking-outside
Laurent
Fiddle showing the above code in action.
Sorry to drag this up after so long but I used the below. Any disadvantages? See the open function...
This question is a bit old, but in case someone wants to close a dialog that is NOT modal when user clicks somewhere, you can use this that I took from the JQuery UI Multiselect plugin. The main advantage is that the click is not "lost" (if user wants to click on a link or a button, the action is done).