0

Let's suppose we have a <div> and some nested elements:

<div id="outer">
  <!-- some code goes here ---> 
  <div id="inner">
    <!-- some code goes here ---> 
  </div>
</div>

Some listener (let's call it onOuterClicked) is bound to #outer and is captured by #inner, which is not what I want. The point is that:

  • I can't alter onOuterClicked (I just have no access to it)

  • I want #inner to call onInnerClicked by click

  • I don't want #inner to call onOuterClicked by click

  • #inner may be added or deleted later

So if I just bind onInnerClicked listener to #inner by jQuery .on, it will anyway call onOuterClicked. How can I avoid it?

Sorry if it's a duplicate question, but all answers I found here are about changing body of onOuterClicked which is not something I can do.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Arsen
  • 43
  • 2
  • 5
  • wrap the call to outer event listener, `outer.addEventListener("click",function(evt){ evt.stopPropagation(); onOuterClicked(evt)},false);` – Saar Sep 27 '15 at 15:25
  • Needs to be a HELL of a reason for "can't" in this situation. Read my answer [HERE](http://stackoverflow.com/questions/32544958/event-handlers-and-listeners-event-bubbling-and-event-capturing/) to get a better understanding of event propagation - and use the example of stopPropagation() Rejith has given you below – Ragdata Sep 27 '15 at 15:28
  • 1
    possible duplicate of [How do I prevent a parent's onclick event from firing when a child anchor is clicked?](http://stackoverflow.com/questions/1369035/how-do-i-prevent-a-parents-onclick-event-from-firing-when-a-child-anchor-is-cli) – Ragdata Sep 27 '15 at 15:35

1 Answers1

0
$(document).on('click', '#inner',function(event){
    if($(event.target).closest('#inner').length == 0 ){
        event.stopPropagation();
    } else {
        onInnerClicked(); 
    }
});
rrk
  • 15,677
  • 4
  • 29
  • 45