Search code examples
javascriptweb-component

Web component interaction with button click event


I have a custom HTML element x-icicle over which I have full control, I would like to have it interact with an HTML button (that could be anywhere in the DOM), e.g., every time the button is pressed I would like some JS to be executed in x-icicle.

<button></button>
<x-icicle></x-icicle>
class Icicle extends HTMLElement {
  // ...
  if (buttom_pressed) {
    // something
  }
}
customElements.define('x-icicle', Icicle);

I do not know how to send the button event to x-icicle. Perhaps setting a callback somehow?

Any hints?


Solution

  • A solution would be to use CustomEvent

    Take a look at the example below (I used a simple span instead of your custom element but it would be exactly the same)

    const button = document.getElementById('button');
    const span = document.getElementById('span');
    
    button.addEventListener('click', evt => {
        span.dispatchEvent(new CustomEvent('myEvent'));
    });
    
    span.addEventListener('myEvent', evt => {
        span.innerHTML = 'button has been clicked';
    });
    <button id="button">button</button>
    <span id="span"></span>