How to detect escape key press?

javascript, jquery, jquery-events, keyevent

Solution

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('keydown', function(e) {
  if (e.key == "Escape") {
    msg.textContent += 'Escape pressed:'
  }
});
Press ESC key <span id="state-msg"></span>

`keyCode` and keypress are deprecated.

It seems `keydown` and `keyup` work.

$(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

Problem

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 } }); ```

Original source

Related problems