views:

154

answers:

2

Let's say I have the following Code:

<div id="parent">
    <div id="child"></div>
</div>

Now I attach an onClick event to the parent div:

$('#parent').click(function() { ... });

Is there an easy way to stop the event from triggering when I click on the child div? I don't want to do something like

$('#child').click(function() { return false; });

because the child div could contain links...

Thanks!

+3  A: 

Check the event target.

The following code is untested.

var div = document.getElementById('parent');
jQuery(div).click(function(event) {
  if (event.target !== div) {
    return false;
  }
});
David Dorward
tested...this works
David Andres
+1  A: 

stopPropagation

$('#child').click(function(event) { 
       event.stopPropagation();
       //...
});
andres descalzo
The question says he doesn't want to attach an event to every child element.
David Dorward
@David Dorward, What says here? "because the child div could contain links..."
andres descalzo
Just to protect this answer a bit: stopPropagation was used but preventDefault wasn't, which means that your links will still fire even though you have a handler assigned to click. jQuery is extremely friendly about the way it adds event handlers to ensure that the default behavior and any previously assigned handlers (i.e., inline with html) still function as expected.
David Andres