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

Mithun Sreedharan picture Mithun Sreedharan · Jul 30, 2010 · Viewed 520.6k times · Source

Possible Duplicate:
Which keycode for escape key with 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
    }
});

Answer

Jigar Joshi picture Jigar Joshi · Jul 30, 2010

Note: keyCode is becoming deprecated, use key instead.

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

Code Snippet:

var msg = document.getElementById('state-msg');

document.body.addEventListener('keypress', function(e) {
  if (e.key == "Escape") {
    msg.textContent += 'Escape pressed:'
  }
});
Press ESC key <span id="state-msg"></span>


keyCode is becoming deprecated

It seems keydown and keyup work, even though keypress may not


$(document).keyup(function(e) {
     if (e.key === "Escape") { // escape key maps to keycode `27`
        // <DO YOUR WORK HERE>
    }
});

Which keycode for escape key with jQuery