I've been trying to implement an event listener for the keydown event for a specific web component. The event listener should be placed within the web component, so it can be used in other projects, too. I implemented an onclick listener which works fine: both methods (for the document and for the shadow dom) are being called. However, this does not work for the keydown event.
I already did some research, however, did not find fitting solutions, e.g. this one. According to this source, the keydown event should be "useable" as is has the composed = true
property.
Below is my sample code. This problems seems to appear also for the keyup and keypress event. I feel like I'm missing an essential point. Is there any possibility to handle keydown events within a shadow dom?
class CustomElement extends HTMLElement {
constructor() {
super();
let template = document.getElementById("custom-template");
this.attachShadow({ mode: "open" });
this.shadowRoot.appendChild(template.content.cloneNode(true));
}
connectedCallback() {
this.shadowRoot.addEventListener("click", (e) => {
alert("click from shadow dom");
});
this.shadowRoot.addEventListener("keydown", (e) => {
e.stopPropagation(); // doesn't seem to change anything
alert("keydown from shadow dom"); // won't run
});
}
}
window.customElements.define("custom-template", CustomElement);
document.addEventListener("click", (e) => {
alert(`click from document; composed: ${e.composed}`);
});
document.addEventListener("keydown", (e) => {
alert(`keydown from document; composed: ${e.composed}`);
});
<custom-template></custom-template>
<template id="custom-template">
<button>Click me</button>
<div>This is a div</div>
</template>