Possible Duplicate:
Prevent click event from affecting parent jquery
I have a DOM structure similar to this:
<div class="parent">
<div class="child">
</div>
</div>
I have the following jQuery:
$('.parent').click(function(){
$(this).hide();
});
When .child
is clicked I don't want the parent to hide but obviously because .child
is a child of .parent
this naturally happens. I've tried adding this:
$('.child').click(function(e){
e.stopPropagation();
});
But it still doesn't work. I've also tried replacing e.stopPropagation
with return false;
any suggestions?
JSFiddle
This definitely works see my fiddle of your code. Try clicking the green div. If it does not work on your site, you have another issue.
Ah well, here's the solution: Fiddle: http://jsfiddle.net/mPUTe/1/.
Don't bind an event listener to the .pu_container
. Instead, check whether e.target
at the .pu_bg
click listener has class pu_container
. If yes, return.
(function($) {
$.fn.show = function() {
return this.each(function() {
var link = $(this);
link.click(function(e) {
$('body').append('<div class="pu_bg">');
$('.pu_bg').css({
'opacity': 0.5
}).on('click', function(e) {
if($(e.target).hasClass('pu_container')) return; //<--Magic?
$(this).fadeOut(function(){
$(this).remove();
});
});;
$('.pu_bg').append('<div class="pu_container">');
e.preventDefault();
});
});
};
})(jQuery);
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