How to Detect Escape Key Press Using jQuery
The keyup and keydown event handler are used to detect pressing any key on a keyboard. The keydown
event indicates the event of pressing
key down and the keyup
event refers to the moment the key is up again after pressing. After capturing the keydown/keyup events, we can detect which key is pressed on the keyboard simply by the event.key
property, and thus we can only react when the escape key is pressed.
<!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.