Search code examples
javascriptjquerystoppropagation

div with onclick inside another div click also firing


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>


Solution

  • 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>