How to Detect Escape Key Press Using jQuery

The keyup and keydown event handler are used to detect escape key press. The event handler triggers over the document when the escape key is pressed in the keyboard.

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
  </head>
  <body>
    <div>Please press the Esc key</div>
    <script>
      $(document).on(
          'keydown',
          function(event) {
            if(event.key == "Escape") {
              alert('Esc key pressed.');
            }
          });
    </script>
  </body>
</html>

You can also use the keyup event handler to detect the escape key press:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
  </head>
  <body>
    <div>Please press the Esc key</div>
    <script>
      $(document).on('keyup', function(event) {
          if(event.key == "Escape") {
            alert('Esc key pressed.');
          }
        });
    </script>
  </body>
</html>

The keydown and keyup Events

The keydown event occurs when any key on the keyboard is pressed. The event is fired for all keys, unlike the keypress.

The keyup event occurs when a key is released. The keydown and keyup events give you a code telling which key is pressed, while keypress tells which character was entered.