DEV Community

Discussion on: Getting Started with Web components

Collapse
 
itachiuchiha profile image
Itachi Uchiha

Thanks!

Actually, I wanted to say;

myCustomElement.addEventListener('mycustomevent', () => {})
Enter fullscreen mode Exit fullscreen mode

How can I do that?

Thread Thread
 
imkarthikeyan profile image
Karthikeyan

You can do that. we just have to tweak our code little bit.


class clickButton extends HTMLElement {
  connectedCallback() {
    this.renderComponent();
    document.getElementById("show-alert").addEventListener("click", () => {
      alert("attaching the click event to web component");
    });
  }

  disconnectedCallback(){
    document.getElementById("show-alert").removeEventListener("click")
  }

  renderComponent() {
    this.innerHTML = `
    <button id="show-alert">add click event</button>
    `;
  }
}

customElements.define("click-button", clickButton);


ClickButton.addEventListener("click",customEvent);

function customEvent(e){
  alert(`targeting the outer ${e.target.tagName}`)
}

Enter fullscreen mode Exit fullscreen mode

<click-button id="ClickButton"></click-button>

Enter fullscreen mode Exit fullscreen mode

Hope this answers your question.

Thread Thread
 
itachiuchiha profile image
Itachi Uchiha

Thanks! :)