Search code examples
javascripteventsweb-component

Fire events in a web-component


I am trying to raise events out of a webcomponent, but it does.

<my-component id="xyz" bez="hallo" hello="myScript()"></my-component>
<script>
    xyz.addEventListener("hello", function(event) {
        console.log(event.detail.name);
    });
</script>

Neither the html-tag "hello" does raise the event, nor the event-listener does.

The web component looks like this:

var button=document.createElement("button");
button.innerHTML=cap;
button.addEventListener('click', () => {
    console.log("click");
        
    button.dispatchEvent(new CustomEvent("hello", {
        detail: { name: "John" }
    }));
});
    
shadow.appendChild(button);

Can anyone help me please to find the mistake? Thanks a lot.

Code-Fiddle here: https://jsfiddle.net/b43uqsLp/2/


Solution

  • The problem occurs because of the Shadow DOM (try to inspect your component and you will see what I mean): enter image description here

    Good news, it's really simple to fix - just propagate the event across the shadow DOM into the regular DOM via composed: true property in your CustomEvent's options:

    button.dispatchEvent(new CustomEvent("hello", {
        detail: { name: "John" },
        composed: true // Like this
    }));
    

    Here is JSFIDDLE.