Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery click on a child ignore parent click [duplicate]

Tags:

jquery

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

like image 934
Lee Price Avatar asked Nov 07 '11 20:11

Lee Price


2 Answers

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.

like image 115
topek Avatar answered Nov 13 '22 11:11

topek


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);
like image 35
Rob W Avatar answered Nov 13 '22 11:11

Rob W