Search code examples
jqueryevent-handlingstoppropagation

jQuery event capturing stop propagation


I have a event listener on a parent div, and i'd like it not to get fired on child div onclick as well.

I'm using jQuery for this, since i need the .on() being the element dynamically created, also the child div is dynamically created with an inline onclick="myFunction()". When the onclick myFunction occurs in the child i don't want the parent .on(click) gets called again.

html:

    <div id="parent" class="areatext" onkeydown="checkR()">
    <div id="input" contenteditable="true" style="min-height:26px;" onkeyup="checkTyping()"></div>
    <div id="child" onclick="myFunction()"></div>
    </div>

js file 1:

$('#parent').on('click', function(event){
    $('#input').focus();
    console.log('parent clicked!');
    event.stopPropagation();
});

js file 2:

function myFunction(event){
   // actions
   // when this is clicked, #parent .on(click) also triggers, i don't want that
}

Solution

  • As you said, jQuery doesn't support listening to events in the capturing phase; you'll have to use standard Javascript instead of jQuery in order to accomplish that. For example:

    const parent = document.querySelector('#parent');
    parent.addEventListener('click', (e) => {
      if (e.target.matches('#child')) return;
      e.stopPropagation();
      console.log('parent was clicked, but not on child');
    }, true);
    function myFunction(event){
       console.log('child was clicked on');
       // when this is clicked, #parent .on(click) also triggers, i don't want that
    }
    <div id="parent" class="areatext">
      parent
      <div id="input" contenteditable="true" style="min-height:26px;" onkeyup="checkTyping()"></div>
      <div id="child" onclick="myFunction()">child</div>
    </div>