I have searched for some time; but only find Polymer answers;
or answers where EventListeners are put on DOM elements inside the shadowRoot.
The effect I am trying to achieve with native Custom Elements:
It is possible to attach a click event to the shadowRoot, it seems I am doing something wrong for the 'keyup' event.
If I put the EventListener
on the window
all elements (of course) update with the same key info.
window.customElements.define('game-toes', class extends HTMLElement {
constructor() {
super().attachShadow({mode:'open'})
.innerHTML = this.tabIndex;
this.addEventListener('keyup',evt=>this.shadowRoot.innerHTML = 'key:'+evt.key);
}
});
game-toes{
display:inline-block;
height:auto;
width:100px;
padding:1em;
border:10px solid green;
}
game-toes:focus {
background-color: lightgreen;
}
<game-toes tabindex=1></game-toes>
<game-toes tabindex=2></game-toes>
<game-toes tabindex=3></game-toes>
You can do it like you were but you need to add some extra code to make it work:
function on(el, evt, cb) {
el.addEventListener(evt, cb);
return () => {
el.removeEventListener(evt, cb);
}
}
window.customElements.define('game-toes', class extends HTMLElement {
constructor() {
super()
.attachShadow({mode: 'open'})
.innerHTML = this.tabIndex;
}
connectedCallback() {
this._offKeyup = on(this, 'keyup', evt => {
this.shadowRoot.innerHTML = evt.key;
evt.stopPropagation(); // Prevent the event from leaving this element
});
}
disconnectedCallback() {
this._offKeyup();
}
});
game-toes{
display:inline-block;
height:auto;
width:100px;
padding:1em;
border:10px solid green;
}
game-toes:focus {
background-color: lightgreen;
}
<game-toes tabindex=1></game-toes>
<game-toes tabindex=2></game-toes>
<game-toes tabindex=3></game-toes>
evt.stopPropagation()
to stop the event from leaving the component.keyup
event on that internal element.connectedCallback
and release them in the disconnectedCallback
unless you never plan to remove your component.