It is possible to attach onClick event to the shadow DOM. Here is how to make it possible
classclickButtonextendsHTMLElement{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);
You can do that. we just have to tweak our code little bit.
classclickButtonextendsHTMLElement{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);functioncustomEvent(e){alert(`targeting the outer ${e.target.tagName}`)}
It is possible to attach onClick event to the shadow DOM. Here is how to make it possible
Thanks!
Actually, I wanted to say;
How can I do that?
You can do that. we just have to tweak our code little bit.
Hope this answers your question.
Thanks! :)