Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}

2 Answers

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>
like image 72
CertainPerformance Avatar answered Mar 31 '26 03:03

CertainPerformance


If you want parent div's click handler not to be called when child div is clicked, you'll have to add event.stopPropagation() in the child div's click event handler.

According to your code:

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

$('#parent').on('click', '.child', function(event){
    event.stopPropagation();
    // ^^^^ Add here
    console.log('child clicked!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent" class="areatext" onkeydown="checkR()">Parent
    <div id="input" contenteditable="true" style="min-height:26px;" onkeyup="checkTyping()"></div>
    <div class="child">child</div>
</div>

I suggest you read https://javascript.info/bubbling-and-capturing to know how bubbling and capturing works in JavaScript.

like image 36
vatz88 Avatar answered Mar 31 '26 03:03

vatz88



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!