Trap ESC keycode in a modal

430    Asked by HannahDyer in Salesforce , Asked on Apr 24, 2021

I want to override the behavior of the ESC key in my LWC while a modal is being displayed. Default behavior passes the ESC key down to the calling component and closes both the modal and that component. I can trap the ESC in the modal with this code:

@track openModal = false; connectedCallback() { this.template.addEventListener('keydown', event => { var keycode = event.code; console.log('keycode',keycode); if(keycode == 'Escape'){ event.preventDefault(); event.stopImmediatePropagation(); } }, true); } showModal() { this.openModal = true; } closeModal() { this.openModal = false; }

HTML

<!-- =============== Information Modal =============== -->

Once I've trapped the ESC key, I want to close the modal. I'm not sure how to make that happen. What is esc keycode?

Answered by Dylan PEREZ

 I would put the handler on the top-level element in your template, rather than dynamically:


Which should allow the esc keycode to be captured correctly:
handleKeyDown(event) { if(event.code == 'Escape') { this.openModal = false; event.preventDefault(); event.stopImmediatePropagation(); } }

Your Answer

Interviews

Parent Categories