Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
135
rated 0 times [  139] [ 4]  / answers: 1 / hits: 142229  / 14 Years ago, wed, march 31, 2010, 12:00:00

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');
});
});

More From » jquery

 Answers
235

Check out the jQuery Outside Events plugin



Lets you do:



$field_hint.bind('clickoutside',function(){
$field_hint.dialog('close');
});

[#97194] Sunday, March 28, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristinsonjab

Total Points: 364
Total Questions: 98
Total Answers: 98

Location: Christmas Island
Member since Mon, Oct 19, 2020
4 Years ago
;