0

I have parent div and inside child div's(many). Parent div had addEventListener with click event. But when i click the inside the child div that one also event firing. I want to stop those things.

Example I have A parent div, and B child div. When i click A div only need to add some logic(get content in b div), when i click the B div don't do anything.

var content= document.querySelector('.test-content');
    content.addEventListener('click', function(evt) {
      var check = this.querySelector('.testClass');
      alert("fired");
      evt = evt || window.event;
      stopPropagation(evt);    
    });
    
 function stopPropagation(evt) {
    if (typeof evt.stopPropagation == "function") {
        evt.stopPropagation();
    } else {
        evt.cancelBubble = true;
    }
  }
<div class="test-content" style="width:100%;height:200px;background-color:yellow" >This is Div A
<div style="width:20%;height:100px;background-color:red"> This is Div B
 <div class="testClass" > test</div>
</div>
</div>
RSKMR
  • 1,812
  • 5
  • 32
  • 73
  • 1
    https://stackoverflow.com/questions/9183381/how-to-have-click-event-only-fire-on-parent-div-not-children – Nagaraj S Nov 15 '17 at 07:31
  • The linked answer is not a true duplicate. That answer tells how to stop child events from firing entirely, this question is about how to stop both the child and parent events from firing when the child is clicked. – Bretton Wade Nov 28 '18 at 15:40

1 Answers1

4

Simply check if evt.target != this before proceeding further.

Demo

var content= document.querySelector('.test-content');
    content.addEventListener('click', function(evt) {
      if ( evt.target != this ) return false; //notice this line
      alert("fired");
      evt = evt || window.event;
      stopPropagation(evt);    
    });
    
 function stopPropagation(evt) {
    if (typeof evt.stopPropagation == "function") {
        evt.stopPropagation();
    } else {
        evt.cancelBubble = true;
    }
  }
<div class="test-content" style="width:100%;height:200px;background-color:yellow" >This is Div A
<div style="width:20%;height:100px;background-color:red"> This is Div B</div>
</div>
gurvinder372
  • 66,980
  • 10
  • 72
  • 94