Search code examples
javascriptjqueryhtmlfunctionstoppropagation

jQuery.on() fails to work with stopPropagation


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?


Solution

  • 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