To do this, stop the click on the child using .stopPropagation:
$(".example").click(function(){
$(this).fadeOut("fast");
}).children().click(function(e) {
return false;
});
This will stop the child clicks from bubbling up past their level so the parent won't receive the click.
.not()
is used a bit differently, it filters elements out of your selector, for example:
<div class="bob" id="myID"></div>
<div class="bob"></div>
$(".bob").not("#myID"); //removes the element with myID
For clicking, your problem is that the click on a child bubbles up to the parent, not that you've inadvertently attached a click handler to the child.
I'm using following markup and had encoutered the same problem:
<ul class="nav">
<li><a href="abc.html">abc</a></li>
<li><a href="def.html">def</a></li>
</ul>
Here I have used the following logic:
$(".nav > li").click(function(e){
if(e.target != this) return; // only continue if the target itself has been clicked
// this section only processes if the .nav > li itself is clicked.
alert("you clicked .nav > li, but not it's children");
});
In terms of the exact question, I can see that working as follows:
$(".example").click(function(e){
if(e.target != this) return; // only continue if the target itself has been clicked
$(".example").fadeOut("fast");
});
or of course the other way around:
$(".example").click(function(e){
if(e.target == this){ // only if the target itself has been clicked
$(".example").fadeOut("fast");
}
});
Hope that helps.
Or you can do also:
$('.example').on('click', function(e) {
if( e.target != this )
return false;
// ... //
});
My solution:
jQuery('.foo').on('click',function(event){
if ( !jQuery(event.target).is('.foo *') ) {
// code goes here
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With