2

I have have a 2 div element. One is child and one is parent like :

<div id="p">
  <div id="c">
  </div>
</div> 

The parent div has 2 event attached click and dblclick and child div has 1 event attached click. Now my problem is when i clicked on the child div the parent div click event also executed. I tried e.stopPropagation(); but still same behavior. Help me ?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Tom Rider
  • 2,747
  • 7
  • 42
  • 65

2 Answers2

5

You must have tried it wrong, because stopPropagation should do the trick here. Make sure you stop the propagation of the event at the child element:

$("#c").click(function (e) {
    e.stopPropagation(); //Will prevent event bubbling to #p
});

Here's a working example.


The only exception to the above is if you have bound the event handlers with the live method (which you shouldn't be doing since live is deprecated). You cannot stop the propagation of live events since the event handler is bound to the document, rather than the element, and the event has to propagate all the way to the document before it is executed.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • If you are stuck using an older version of jQuery `.delegate()` will work and stopPropagation works with it as well. Just a tip :) – rlemon Jun 22 '12 at 15:24
0

Beside using stopPropagation you can also check for a condition before handling the event (an event delegation approach). This way you can also use live event handlers (replaced by on in jQuery nowadays, if I'm correct). See this fiddle

[edit]: using bind, you'll only need one handler for all, defined for div#p. The provided jsfiddle is adjusted accordingly.

KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • `live` is deprecated... and also `delegate` should be used over live for older versions (and bind in the oldest of old)... `stopPropagation` does not work in `live` - also `live` is slow and cannot be chained. http://api.jquery.com/live/ see here – rlemon Jun 22 '12 at 15:22
  • I didn't say he *had* to use `live`, I merely pointed to it as a possibility. Event delegation, furthermore, doesn't have to be at document level per se. It's perfectly usable at the level of some root element, and handy for, say, xhr refreshed sub-elements of such an element. In case of the jsfiddle I provided, it's merely a click handler on a root element. – KooiInc Jun 22 '12 at 15:27