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:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!