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)
<!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> |
Output before pressing escape:

Output after pressing escape:

Example-2: This example detects the escape key press (using keyup event handler)
<!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> |
Output before pressing escape:

Output after pressing escape:

Recommended Posts:
- How to detect a mobile device in jQuery?
- How to detect the user's device using jQuery ?
- JQuery | Detect a textbox content is changed or not
- Detect a device is iOS or not using JavaScript
- How to detect browser or tab closing in JavaScript ?
- How to detect when user scrolls to the bottom of a div ?
- How to detect if a function is called as constructor?
- How to detect flash is installed or not using JavaScript ?
- jQuery | jQuery.support Property
- jQuery | jQuery.fx.interval Property with example
- How to detect touch screen device using JavaScript?
- Detect the Operating System of User using JavaScript
- How to detect operating system on the client machine using JavaScript ?
- jQuery | jQuery.fx.off Property
- jQuery | jquery Property
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.



