6

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.

Community
  • 1
  • 1
gubbfett
  • 2,157
  • 6
  • 32
  • 54

6 Answers6

12

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.

Tjirp
  • 2,435
  • 1
  • 25
  • 35
5

Try this:

$('#parent').click(function(data, handler){
  if (data.target == this) {
    //Do Stuff (only element clicked, not children)
  }
});
Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
1

h1 is not the parent, div#parent is the parent. clicking div#child triggers click on div#parent because of event bubbling. this will prevent event bubbling:

$('#child').on("click", function() {
    return false;
});
David Fregoli
  • 3,377
  • 1
  • 19
  • 40
1

The easiest solution is to check that the element that originated the event (event.target) is the same as the element handling the click event handler (this):

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

Here's a working jsFiddle.

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
0

You can try something like:

$(document).ready(function(){
    $('#parent h1').click(function(){
        alert('Parent was clicked');
    });
});
ioan
  • 489
  • 2
  • 4
0
$(document).ready(function(){
  $('#parent').click(function(){
    if($(this).not("#parent")) {
      return false;
    } else {
      alert('Parent was clicked');
    };
  });
});