Reputation: 680
I have html structure like below:
<div id="banner-menu-holder">
<div>
<div class="avalible">
<div class="items-holder">
<div>
<div class="img-holder">
<div>
<input id="set_banner_29" type="checkbox" onclick="mod.setBanner(29);">
...
</div>
</div>
</div>
...
</div>
</div>
<div class="ready">
<div class="items-holder">
<div>
<div class="img-holder">
<div>
<input id="rem_banner_1_8_32" class="remove_banner" type="checkbox" checked="checked">
...
</div>
</div>
</div>
...
</div>
</div>
</div>
</div>
and js code:
$(document).click(function(ev) {
if ($(ev.target).parents().index($('#banner-menu-holder')) == -1) {
$('#banner-menu-holder').css('display', 'none');
}
})
When I clicked checkbox into first div (class avalible) then function has been successfull executed - this chekbox is child of main div (#banner-menu-holder).
When I clicked second div's checkboxes and the function had not worked. jQuery didn't detected that these checkboxes are children of main div.
Is that problem into jQuery or otherwise?
Upvotes: 0
Views: 111
Reputation: 3694
Seems like you're doing event delegation, but in a very clunky way.
jQuery makes this easier with .on()
.
$(document).on('click', '#banner-menu-holder', function(ev) {
$('#banner-menu-holder').css('display', 'none');
});
$(document).on('click', ':not(#banner-menu-holder)', function(ev) {
$('#banner-menu-holder').css('display', 'none');
});
If you're using jQuery 1.4-1.6.x, you'd use .delegate()
instead.
$(document).delegate('#banner-menu-holder', 'click', function(ev) {
$('#banner-menu-holder').css('display', 'none');
});
$(document).delegate(':not(#banner-menu-holder)', 'click', function(ev) {
// do something else
});
Upvotes: 1
Reputation: 337560
Try using closest()
to check if the current element has a parent with the banner-menu-holder
id:
if (!$(ev.target).closest('#banner-menu-holder').length) {
$('#banner-menu-holder').css('display', 'none');
}
Upvotes: 2
Reputation: 488424
I'm not exactly sure what you are trying to do, but if you are trying to see if the clicked element is inside the #banner-menu-holder
element I would write it like this:
if($(ev.target).closest('#banner-menu-holder').length > 0) {
...
}
Upvotes: 1