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: