Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to detect escape key press with pure JS or jQuery?

How to detect escape key press in IE, Firefox and Chrome? Below code works in IE and alerts 27, but in Firefox it alerts 0

$('body').keypress(function(e){
alert(e.which);
if(e.which == 27){
// Close my modal window
}
});
by

3 Answers

espadacoder11
Using JavaScript you can do check working jsfiddle

document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
};

Using jQuery you can do check working jsfiddle

jQuery(document).on('keyup',function(evt) {
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
});
pankajshivnani123
check for keyCode && which & keyup || keydown

$(document).keydown(function(e){
var code = e.keyCode || e.which;
alert(code);
});
sandhya6gczb
Note: keyCode is becoming deprecated, use key instead.

function keyPress (e) {
if(e.key === "Escape") {
// write your logic here.
}
}

Login / Signup to Answer the Question.