javascripthtmlcustom-events

Why CustomEvent remains unhandled in JS code


I'm trying to fire up a custom event and catch it by a child element, which doesn't seem to work. What am I missing (I am aware of DOM-less solutions, but need to get it working with DOM)?

I tried a few different options including swapping child and parent to eliminate potential bubbling/tunneling issues, and tried the legacy Event class, but none seemed to work.

document.getElementById("parent").addEventListener("click", function() {
  window.dispatchEvent(new CustomEvent("test", {
    detail: "Hello"
  }));
});



document.getElementById("child").addEventListener("test", function(event) {
  console.info("Hello");
});
<button id="parent">Fire</button>
<div id="child" />


Solution

  • The issue is because you've assigned the test event listener to the #child element, but you're triggering it against the window.

    To fix the problem, listen for the event on the element you raise it on, or one of its parents.

    const parent = document.querySelector('#parent');
    const child = document.querySelector('#child');
    
    parent.addEventListener("click", () => {
      child.dispatchEvent(new CustomEvent("test", {
        detail: "Hello"
      }));
    });
    
    child.addEventListener("test", e => {
      console.info(e.detail);
    });
    <button id="parent">Fire</button>
    <div id="child" />