How to detect escape key press using jQuery?

To detect escape key press, keyup or keydown event handler will be used in jquery. It will trigger over the document when the escape key will be pressed from the keyboard.

  • keyup event: This event is fired when key is released from the keyboard.
  • keydown event: This event is fired when key is pressed from the keyboard.

Syntax:

$(document).on('keydown', function(event) {
       if (event.key == "Escape") {
           alert('Esc key pressed.');
       }
   });

Explanation:
Over whole document we are calling the on method and we are passing the keydown or keyup event as first parameter. As second parameter a function is attached which invokes when keydown or keyup event occurs and it will show an alert on pressing the escape key from the keyboard.

Example-1: This example detects the escape key press(using keydown event handler)

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <title>
      escape-jquery-detection
  </title>
    <script src=
  </script>
</head>
  
<body>
    <h1>
      Escape jquery detection
      using keydown event handler
  </h1>
</body>
  
<script>
    $(document).on(
      'keydown', function(event) {
        if (event.key == "Escape") {
            alert('Esc key pressed.');
        }
    });
</script>
  
</html>

chevron_right


Output before pressing escape:

Output after pressing escape:

Example-2: This example detects the escape key press (using keyup event handler)

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <title>
      escape-jquery-detection
  </title>
    <script src=
  </script>
</head>
  
<body>
    <h1>
Escape jquery detection using keyup event handler
  </h1>
</body>
  
<script>
    $(document).on('keyup', function(event) {
        if (event.key == "Escape") {
            alert('Esc key pressed.');
        }
    });
</script>
  
</html>

chevron_right


Output before pressing escape:

Output after pressing escape:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.