jQuery UI - Close Dialog When Clicked Outside
- by Sonny
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
$(document).ready(function() {
var $field_hint = $('<div></div>')
.dialog({
autoOpen: false,
minHeight: 50,
resizable: false,
width: 375
})
.bind('clickoutside', function(e) {
if (!$(e.target).filter('.hint').length) {
$field_hint.dialog('close');
}
});
$('.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');
});
});