How to Close a Modal Popup Using the ESC Key in JavaScript

Learn how to easily close a modal popup with the ESC key using a simple JavaScript event listener for improved user experience.

0 views

To close a modal popup with the ESC key, you can add a JavaScript event listener to the document that listens for the `keydown` event. When this event occurs, check if the key pressed is the ESC key (key code 27). If so, execute the code to close the modal. Here’s a quick example: `document.addEventListener('keydown', function(event) { if(event.keyCode === 27) { // Code to close modal goes here } });` This solution enables user-friendly navigation by allowing modals to be easily dismissed with a keystroke.

FAQs & Answers

  1. What is the key code for the ESC key in JavaScript? The key code for the ESC key in JavaScript is 27.
  2. How can I add a keyboard shortcut to close a modal popup? You can add a 'keydown' event listener to the document and check if the pressed key is the ESC key to trigger the modal close function.
  3. Why should I enable closing modals with the ESC key? Allowing users to close modals with the ESC key improves accessibility and user experience by providing a quick, keyboard-based method to dismiss popups.