How do you stop children from propagating an event triggered by a live/delegate listener?

qodeninja picture qodeninja · Feb 5, 2012 · Viewed 7.3k times · Source

I have a delegation parent that listen for click events in a set of children with a specific class.

$(".toggle_group").on("click",".toggle",function(e){ .. });

so heres an example of the html

<div class='toggle_group'>
  <a class='toggle'>click me and i toggle <div>Im a child of toggle</div></a>
  <a class='toggle'>click me and i toggle <div>Im a child of toggle</div></a>
  <a class='toggle'>click me and i toggle <div>Im a child of toggle</div></a>
  <a class='toggle'>click me and i toggle <div>Im a child of toggle</div></a>
</div>

the problem is that children of a.toggle propogate the event to the parent triggering the handler when it shouldn't. According to jQuery docs you cant stop event propagation on live/delegated event listeners.

How do I stop these sub children of a.toggle from propogating the event to the parent? or maybe in some cases permit it?

You see the inner div of .toggle is supposed to be a drop down menu. It shouldnt toggle when you click the menu, only when you click the toggle link...

Answer

Teemu Ikonen picture Teemu Ikonen · Feb 5, 2012

Check the comments in this page, at least some claim to have found workaround. http://api.jquery.com/event.stopPropagation/

Copied the comment from thread here for future reference:

MikeW: work around for .live() event propagation issues. nodes created dynamically will not receive the event until after their parent has received it. this will cause funkyness and stopPropagation and preventDefault will not solve this issue. To Fix: add the lines

if(event.target != this){ return true; }

to the top of the parent nodes event handler. this will stop the parent event from firing when the event is actually addressed to a child node, and (unlike return false) will propagate the event to the intended node.