3

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...

qodeninja
  • 10,946
  • 30
  • 98
  • 152
  • 1
    you do this with .off() on the children – frenchie Feb 05 '12 at 22:12
  • so youre saying that children with inherited event listeners should use off to disable them? – qodeninja Feb 06 '12 at 00:33
  • 1
    yes, that's one way to do it. StopPropagation is another way to do it. Yet another way to do it would be to create an event listener for the children div with on() and have it do nothing. – frenchie Feb 06 '12 at 10:13

2 Answers2

5

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.

Teemu Ikonen
  • 11,861
  • 4
  • 22
  • 35
3

Another approach is to only execute your function handler if the event comes from an element with the .toggle class (or one of its children), not the .toggle_group element itself.

$(".toggle_group").on("click",".toggle",function(e){
    if (!$(e.target).is(".toggle")) return;

    ...
});
andytuba
  • 187
  • 9