[SalesForce] Keypress ESC in LWC

I'm looking to add a listener for key "ESC" pressed during interaction with a modal to close it. Because of DOM containment, it seems that I should NOT be using window or document to add a listener for the keypress. What is the correct way to do this in LWC?

document example:

document.onkeypress = function (e) {
e = e || window.event;
// use e.keyCode
};

window example:

window.addEventListener("keyPress", myEventHandler, false);

Best Answer

keyboard up / down events normally should cross the shadow boundary. One important thing is that if you want to listen on div elements that they need a tabindex in order to be "selectable".

On this playground you can see the lwc-recipes modal component which has a direct key up listener. Click on button => shows modal (and get autofocused) => pressing Escape will hide it again

Edit based on Comment: As Alternative the Listener can also be set in the parent component as showcased on this playground

Related Topic