javascripthtmldomevent-propagationcustom-event

Propagation of custom events


I expect my CustomEvent to be propagated from document to all the DOM elements. For some reason, it does not happen. What am I doing wrong?

<html>
<script>
function onLoad() {
  var myDiv = document.getElementById("myDiv");
  myDiv.addEventListener("myEvent",function(){alert("Yes!");});
  document.dispatchEvent(new CustomEvent("myEvent",{detail:null}));
}
</script>
<body onload="onLoad()">
<div id="myDiv"></div>
</body>
</html>

Solution

  • By default Custom Events are not bubbled.

    Reason being, Custom Event definition says:

    let event = new CustomEvent(type,[,options]).

    Options have a flag : bubbles, which is false by default, we have to enable it.

    Following will fix your code

    <html>
    <script>
    function onLoad() {
      var myDiv = document.getElementById("myDiv");
      myDiv.addEventListener("myEvent",function(){alert("Yes!");});
      document.dispatchEvent(new CustomEvent("myEvent",{detail:null,bubbles:true}));
    }
    </script>
    <body onload="onLoad()">
    <div id="myDiv"></div>
    </body>
    </html>