Reputation: 47945
This is my code :
<div id="container">
<div id="box">
Content
</div>
</div>
#container
{
position:relative;
width:400px;
height:400px;
background-color:red;
}
#box
{
position:absolute;
width:200px;
height:200px;
top:100px;
left:100px;
background-color:blue;
}
$('#container:not(#box)').click(function (e) {
e.preventDefault();
$('#container').fadeOut(300);
});
I want to fadeOut
only clicking on the parent (the red div). If I click on the blue one (the child) nothing should happens. How can I do this with jQuery? tried with :not
but seems this is not the right solution...
Upvotes: 2
Views: 921
Reputation: 6147
$('#container').click(function () {
$('#container').fadeOut(300);
});
$('#box').click(function (e) {
e.stopPropagation()
});
Upvotes: 0
Reputation: 14747
When you click on the #box
, the click
event also registers on the parent #container
element because the event bubbles up.
There's two ways top-of-head to prevent that.
First is to stop the bubbling from happening. You do that by calling e.stopPropagation()
on the #box
click handler. But, of course, you've got no #box
event handler, so the next one is a bit more attractive.
Second is to check from the #container
event handler whether or not you're clicking the actual #container
or some child and that the event just bubbled up. You can do this by inspecting the e.target
element, and comparing that to this
in the #container
event handler.
Upvotes: 3
Reputation: 75317
All you need to do it check whether the element the event originated from (e.target
) is the #container
(this
):
$('#container').click(function (e) {
if (e.target === this) {
$('#container').fadeOut(300);
}
});
Upvotes: 6