Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Child is capturing clicks, only want Parent

Tags:

jquery

click

Say i have this:

<div id="outer">
 <div id="inner">
 </div>
</div>

The outer div's dimensions are 500x500, and the inner is 100x100. I'm trying to employ the following:

$('#outer').click(function() {
    $('#outer').fadeOut();
});

But when you click on the 100x100 area of #inner, it still fades out. How to prevent this?

like image 362
steve Avatar asked Nov 04 '10 04:11

steve


2 Answers

I figured out that this code works better, and is not dependent on knowing the element's id or class:

$('#outer').click(function(e) {
    if (e.target === this){
        $('#outer').fadeOut();
    }
});
like image 158
Cristian Avatar answered Nov 02 '22 16:11

Cristian


Better not to assign click handlers for the inner elements. In the click function check event target equal to outer. Something like

$('#outer').click(function(e) {
    if (e.target.id === "outer"){
        $('#outer').fadeOut();
    }
});

Working Demo

like image 19
rahul Avatar answered Nov 02 '22 14:11

rahul