Search code examples
javascriptinlinecustom-elementcustom-events

Custom Elements do not fire inline custom events


I tried to catch inline custom events from custom elements with the following code. I got only 'external success', never 'inline success' on logs.

Any ideas? Thank you.

Note : I have tried also to replace HTMLELement by HTMLDivElement/is: same result

customElements.define(
'test-it',class extends HTMLElement {
  connectedCallback() {
    this.children[0].addEventListener('click', e=>this.dispatchEvent(new CustomEvent('testevent', {detail:'test'})))
  };
}
);

document.getElementsByTagName('test-it')[0].addEventListener('testevent', ()=>{console.log('external success')});
<test-it id="test" ontestevent="console.log('inline success');">
  <div>Minimal test</div>
</test-it>


Solution

  • testevent is not a valid HTML5 Global Event Handler:

    That means ontestevent="..." is just an attribute and not a onEvent handler.

    You can not create such a handler yourself.

    That is why addEventListener was created

    PS. For your future Web Components adventures: Sending Events from inside shadowDOM (you are not using now) require composed:true for CustomEvents to escape shadowDOM