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:
JavaScript
x
21
21
1
$(document).ready(function() {
2
var $field_hint = $('<div></div>')
3
.dialog({
4
autoOpen: false,
5
minHeight: 50,
6
resizable: false,
7
width: 375
8
});
9
10
$('.hint').click(function() {
11
var $hint = $(this);
12
$field_hint.html($hint.html());
13
$field_hint.dialog('option', 'position', [162, $hint.offset().top + 25]);
14
$field_hint.dialog('option', 'title', $hint.siblings('label').html());
15
$field_hint.dialog('open');
16
});
17
/*$(document).click(function() {
18
$field_hint.dialog('close');
19
});*/
20
});
21
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
JavaScript
1
33
33
1
$(document).ready(function() {
2
// dialog element to .hint
3
var $field_hint = $('<div></div>')
4
.dialog({
5
autoOpen: false,
6
minHeight: 0,
7
resizable: false,
8
width: 376
9
})
10
.bind('clickoutside', function(e) {
11
$target = $(e.target);
12
if (!$target.filter('.hint').length
13
&& !$target.filter('.hintclickicon').length) {
14
$field_hint.dialog('close');
15
}
16
});
17
18
// attach dialog element to .hint elements
19
$('.hint').click(function() {
20
var $hint = $(this);
21
$field_hint.html('<div style="max-height: 300px;">' + $hint.html() + '</div>');
22
$field_hint.dialog('option', 'position', [$hint.offset().left - 384, $hint.offset().top + 24 - $(document).scrollTop()]);
23
$field_hint.dialog('option', 'title', $hint.siblings('label').html());
24
$field_hint.dialog('open');
25
});
26
27
// trigger .hint dialog with an anchor tag referencing the form element
28
$('.hintclickicon').click(function(e) {
29
e.preventDefault();
30
$($(this).get(0).hash + ' .hint').trigger('click');
31
});
32
});
33
Advertisement
Answer
Check out the jQuery Outside Events plugin
Lets you do:
JavaScript
1
4
1
$field_hint.bind('clickoutside',function(){
2
$field_hint.dialog('close');
3
});
4