Search code examples
javascripthtmldom-eventsevent-bubbling

dispatch Event on the most inner element doesn't cause bubbling to upper elements?


innerDiv = document.getElementById("inner");
innerDiv.onclick = function(e) {
  console.log("PURPLE COLOR DIV");

}

outterDiv = document.getElementsByClassName("outter")[0];
outterDiv.onclick = function(e) {
  console.log("ORANGE COLOR DIV");
};

containerDiv = document.getElementsByClassName("container")[0];
containerDiv.onclick = function() {
  console.log("RED COLOR DIV");
}

setTimeout(() => document.getElementById("inner").dispatchEvent(new Event('click'), {
  bubbles: true
}), 2000)
.container {
  width: 260px;
  height: 170px;
  background-color: maroon;
  padding-top: 40px;
}

.outter {
  width: 200px;
  height: 80px;
  background: orange;
  margin: 0 auto;
  padding-top: 35px;
}

#inner {
  background: purple;
  width: 100px;
  height: 50px;
  margin: auto;
}
<div class="container">
  <div class="outter">
    <div id="inner"></div>
  </div>
</div>

PROBLEM

After setTimeout causes the dispatchEvent to fire, the Orange and Red color callbacks do not execute. Why is that so if bubbles property is set to true? In case of clicking on the UI purple div, the bubbling does its job as supposed.

Fiddle example: http://jsfiddle.net/0tko5qwe/


Solution

  • You need to add the options to the Event() constructor itself:

    new Event('click', { bubbles: true})
    

    innerDiv = document.getElementById("inner");
    innerDiv.onclick = function(e) {
      console.log("PURPLE COLOR DIV");
    
    }
    
    outterDiv = document.getElementsByClassName("outter")[0];
    outterDiv.onclick = function(e) {
      console.log("ORANGE COLOR DIV");
    };
    
    containerDiv = document.getElementsByClassName("container")[0];
    containerDiv.onclick = function() {
      console.log("RED COLOR DIV");
    }
    
    setTimeout(() => document.getElementById("inner").dispatchEvent(new Event('click', {
      bubbles: true
    })), 500)
    .container {
      width: 260px;
      height: 170px;
      background-color: maroon;
      padding-top: 40px;
    }
    
    .outter {
      width: 200px;
      height: 80px;
      background: orange;
      margin: 0 auto;
      padding-top: 35px;
    }
    
    #inner {
      background: purple;
      width: 100px;
      height: 50px;
      margin: auto;
    }
    <div class="container">
      <div class="outter">
        <div id="inner"></div>
      </div>
    </div>