Question

I want to stop func() from being executed when I click the inner div.

this is the html:

    <div onclick="func()">
       <div id="inner-div">
          I'm an inner div
       </div>
     </div>

This code will stop propagation:

$('#inner-div').bind("click", function(e){
  e.stopPropagation();
})

This code fails to stop propagation:

$(document).on("click", '#inner-div' , function(e){
  e.stopPropagation();
})

How do I do it?

Was it helpful?

Solution 2

And to solve it you could do:

<div onclick="func(event, this)">
   <div id="inner-div">
      I'm an inner div
   </div>
 </div>

JS

function func(e, that) {
    if (e.target === that) {
        // do stuff
    }
}

FIDDLE

or use jQuery and remove the inline handler (as the question is tagged jQuery)

<div id="parent">
   <div id="inner-div">
      I'm an inner div
   </div>
 </div>

JS

$(document).on('click', '#parent', function(e) {
    if (e.target === this) {
        // do stuff
    }
});

FIDDLE

OTHER TIPS

Stopping propagation from a delegated handler will not work, since the event has already propagated up the document tree in order for that delegated handler to run.

This is mentioned in the documentation:

Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events.

on() and delegate() behave the same as live() in this context, only with an ancestor element instead of the document itself. In all cases, it is too late to stop the event from propagating from the target element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top