Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click on parent, ignore its children [duplicate]

Possible Duplicate:
jQuery: click function exclude children.

I have two divs, something like this:

<div id="parent" style="width: 100%; height: 100%; background-color:red;" />
    <h1>I'm the parent!</h1>
    <div id="child" style="width: 300px; height: 200px; background-color:yellow;">
        </h2>..and I'm the child!</h2>
    </div>
</div>

Additionally, I have the following JavaScript code:

$(document).ready(function(){
    $('#parent').click(function(){
        alert('Parent was clicked');
    });
});

The problem is, if I click on the child, the event is triggered. How can I limit this event to the parent only?

Edit: Just to clarify; I want this action to trigger when the user clicks anywhere in the red. As said in the comments; the h1 is not the parent. Tjirp's answer did the trick, and there's a lots of working variants of this solution in the answers.

like image 496
gubbfett Avatar asked Jan 31 '13 13:01

gubbfett


Video Answer


2 Answers

This should work

$(document).ready(function() {
    $('#parent').click(function(e) {
        if (e.target == this) { 
            alert('Parent was clicked');
        }
    }
}

This way you won't have to bind anything to your childs. The click event is propagated to your click handler, and it checks if the target of the click event is indeed the element you added the event on.

Edit: I was right. this is not the most efficient way, Alessandro Minoccheri answer should be way faster. I updated my code with his.

like image 194
Tjirp Avatar answered Sep 19 '22 21:09

Tjirp


Try this:

$('#parent').click(function(data, handler){
  if (data.target == this) {
    //Do Stuff (only element clicked, not children)
  }
});
like image 40
Alessandro Minoccheri Avatar answered Sep 21 '22 21:09

Alessandro Minoccheri