2

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);
2
  • 3
    Can't you register the listener on your outer-most element in your LWC template (that isn't a template element)?
    – Phil W
    Aug 11, 2019 at 9:33
  • Tried that with no luck. Adding onkeypress={handleKeyPress} on the outtermost div doesn't fire the event. Not sure if it is a question of the element not having focus. I'll try to find the element with querySelector and add on init but I would assume it is the same. Aug 11, 2019 at 10:12

1 Answer 1

6

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

4
  • Thank you Renji! Unfortunately, I have drag and drop functionality within the modal that can be actionable via key (just like the app launcher). The intent is that focus is not necessary as it will be under the user's control. Aug 12, 2019 at 7:42
  • 1
    not really sure if i am understanding your case 100% but even with drag&drop your component will have at some time focus (also the example was listening on the whole document fragment - not just an element of the modal)... but even listening on key events in your parent component which embeds the modal component and then hides it on esc should work => developer.salesforce.com/docs/component-library/tools/… That example adds a programmatic event listener without any focus state of the modal
    – Renji-xD
    Aug 12, 2019 at 8:59
  • I was not able to get the div element (X utility icon) to work even with tabindex set on it. But with the event listener registered during connectedCallback on the component that holds the modal it works like a charm! TY Aug 12, 2019 at 9:27
  • These links are now out of date. In future please add the relevant code into the answer, rather than link to external resources. That should prevent this happening again. Sep 30, 2021 at 12:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .