591

I have two functions. When enter is pressed the functions runs correctly but when escape is pressed it doesn't. What's the correct number for the escape key?

$(document).keypress(function(e) { 
    if (e.which == 13) $('.save').click();   // enter (works as expected)
    if (e.which == 27) $('.cancel').click(); // esc   (does not work)
});
3
  • Keypress will return a character connected to a key ( in correct caps etc ), Keyup will return the number of hardware button pressed. For ESC you'd want the hardware code 27 ( not the ascii character 27 )
    – Joeri
    Commented Sep 30, 2015 at 19:40
  • Possible duplicate of How to detect escape key press with JavaScript or jQuery?
    – kartik
    Commented Nov 22, 2016 at 6:09
  • 1
    There is a really simple trick to find out whichever keyCode you want. Just open a new tab, put document.addEventListener("keydown", e => console.log(e.keyCode)) into your browser console, click into the window and press the key you are looking for.
    – Wu Wei
    Commented Nov 20, 2019 at 14:31

16 Answers 16

975

Try with the keyup event:

$(document).on('keyup', function(e) {
  if (e.key == "Enter") $('.save').click();
  if (e.key == "Escape") $('.cancel').click();
});
12
  • 39
    This has nothing to do with keyup vs. keypress. To capture ESCAPE, you need to look at e.keyCode as opposed to e.which (which this example happens to do).
    – dkamins
    Commented May 12, 2010 at 3:31
  • 219
    "This has nothing to do with keyup vs. keypress" - that's incorrect, dkamins. keypress doesn't seem to be handled consistently between browsers (try out the demo at api.jquery.com/keypress in IE vs Chrome vs Firefox -- sometimes it doesn't register, and both 'which' and 'keyCode' vary) whereas keyup is consistent. e.which is the jquery-normalized value, so 'which' or 'keyCode' should both work in keyup. Commented May 13, 2010 at 3:04
  • 14
    @Jordan Brough - I would like to request you to post your comment as answer so that people read it and understand the actual meaning of your comment! since your comment is as important as the answer explaining
    – Murtaza
    Commented Feb 3, 2012 at 9:06
  • 15
    keydownwill mimic native behaviour - at least on Windows where pressing ESC or Return in a dialog will trigger the action before the key is released.
    – thomthom
    Commented Oct 31, 2012 at 13:29
  • 2
    @gibberish I've added my comment as an answer here: stackoverflow.com/a/28502629/58876 Commented Feb 13, 2015 at 15:14
85

Rather than hardcode the keycode values in your function, consider using named constants to better convey your meaning:

var KEYCODE_ENTER = 13;
var KEYCODE_ESC = 27;

$(document).keyup(function(e) {
  if (e.keyCode == KEYCODE_ENTER) $('.save').click();
  if (e.keyCode == KEYCODE_ESC) $('.cancel').click();
});

Some browsers (like FireFox, unsure of others) define a global KeyEvent object that exposes these types of constants for you. This SO question shows a nice way of defining that object in other browsers as well.

12
  • 16
    What, 27 doesn't just jump out at you as being the escape key?!? Honestly, this really needs to be done by more people. I call them "magic numbers" and "magic strings." What does 72 mean? Why do you have a very specific and volatile string copy-pasted 300 times in your code base? etc.
    – vbullinger
    Commented Aug 13, 2012 at 20:26
  • 8
    @IvanDurst you may only be using them once per method, but I use them multiple times in my project(s). Are you really suggesting that you'd want to (1) look up the values and (2) comment them every time you want to use a key code? I don't know about you, but I have neither the desire to memorize them nor the faith that other programmers will comment them consistently. It's about making coding easier and more consistent, not just more readable. Commented Mar 2, 2014 at 13:49
  • 2
    Someone who knows what they mean doesn't have to lookup the meaning to comment them, and typing a comment is just as quick as typing a long name.
    – NetMage
    Commented Jul 9, 2014 at 18:13
  • 2
    Not that I'm in any way against named constants, but I think it's worth noting that ENTER can be considered the exceptional case. It doesn't strike me as bad form if someone chooses to use 13 "raw" and commentless since it's a reasonable expectation that all web developers will read it as "enter" without confusion.
    – Semicolon
    Commented Aug 9, 2014 at 0:06
  • 7
    Whatever happened to the good old days when we used to code character constants in hex? Everyone know ESC is 0x1B and Enter is 0x0D, right? Commented Apr 13, 2015 at 15:07
52

(Answer extracted from my previous comment)

You need to use keyup rather than keypress. e.g.:

$(document).keyup(function(e) {
  if (e.which == 13) $('.save').click();     // enter
  if (e.which == 27) $('.cancel').click();   // esc
});

keypress doesn't seem to be handled consistently between browsers (try out the demo at http://api.jquery.com/keypress in IE vs Chrome vs Firefox. Sometimes keypress doesn't register, and the values for both 'which' and 'keyCode' vary) whereas keyup is consistent.

Since there was some discussion of e.which vs e.keyCode: Note that e.which is the jquery-normalized value and is the one recommended for use:

The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.

(from http://api.jquery.com/event.which/)

1
27

To find the keycode for any key, use this simple function:

document.onkeydown = function(evt) {
    console.log(evt.keyCode);
}
0
18

27 is the code for the escape key. :)

2
  • 1
    I have two functions when enter is press the functions runs correctly but not with escape key.. $(document).keypress(function(e) { if (e.which == 13) { $('.save').click(); } if (e.which == 27) { $('.cancel').click(); } });
    – Shishant
    Commented Jul 21, 2009 at 15:43
  • $(document).keypress(function(e) { y=e.keyCode?e.keyCode:e.which;}); When I alert(y), it alerts 27 in IE and FF. Are you sure there's not something else wrong with your code?
    – Salty
    Commented Jul 21, 2009 at 15:51
15

Your best bet is

$(document).keyup(function(e) { 
    if (e.which === 13) $('.save').click();   // enter 
    if (e.which === 27) $('.cancel').click(); // esc   

    /* OPTIONAL: Only if you want other elements to ignore event */
    e.preventDefault();
    e.stopPropagation();
});

Summary

  • which is more preferable than keyCode because it is normalized
  • keyup is more preferable than keydown because keydown may occur multiple times if user keeps it pressed.
  • Do not use keypress unless you want to capture actual characters.

Interestingly Bootstrap uses keydown and keyCode in its dropdown component (as of 3.0.2)! I think it's probably poor choice there.

Related snippet from JQuery doc

While browsers use differing properties to store this information, jQuery normalizes the .which property so you can reliably use it to retrieve the key code. This code corresponds to a key on the keyboard, including codes for special keys such as arrows. For catching actual text entry, .keypress() may be a better choice.

Other item of interest: JavaScript Keypress Library

10

Just posting an updated answer than e.keyCode is considered DEPRECATED on MDN.

Rather you should opt for e.key instead which supports clean names for everything. Here is the relevant copy pasta

window.addEventListener("keydown", function (event) {
  if (event.defaultPrevented) {
    return; // Do nothing if the event was already processed
  }

  switch (event.key) {
    case "ArrowDown":
      // Do something for "down arrow" key press.
      break;
    case "ArrowUp":
      // Do something for "up arrow" key press.
      break;
    case "ArrowLeft":
      // Do something for "left arrow" key press.
      break;
    case "ArrowRight":
      // Do something for "right arrow" key press.
      break;
    case "Enter":
      // Do something for "enter" or "return" key press.
      break;
    case "Escape":
      // Do something for "esc" key press.
      break;
    default:
      return; // Quit when this doesn't handle the key event.
  }

  // Cancel the default action to avoid it being handled twice
  event.preventDefault();
}, true);
3
  • 3
    But it seems to be only supported in Firefox and Chrome. Commented Feb 4, 2018 at 6:58
  • Here is a long list of key values.
    – Bob Stein
    Commented Nov 19, 2019 at 2:52
  • Unfortunately, at least some versions of Internet Explorer pass the code Esc rather than the standard Escape. Commented Apr 9, 2020 at 4:15
9

Try the jEscape plugin (download from google drive)

$(document).escape(function() { 
   alert('ESC button pressed'); 
});

or get keycode for cross browser

var code = (e.keyCode ? e.keyCode : e.which);
if (code === 27) alert('ESC');
if (code === 13) alert('ENTER');

maybe you can use switch

var code = (e.keyCode ? e.keyCode : e.which);
switch (code) {
    case 27:
       alert('ESC');
       break;
     case 13:
       alert('ENTER');
       break;
}
0
8

Your code works just fine. It's most likely the window thats not focused. I use a similar function to close iframe boxes etc.

$(document).ready(function(){

    // Set focus
    setTimeout('window.focus()',1000);

});

$(document).keypress(function(e) {

    // Enable esc
    if (e.keyCode == 27) {
      parent.document.getElementById('iframediv').style.display='none';
      parent.document.getElementById('iframe').src='/views/view.empty.black.html';
    }

});
8

I'm was trying to do the same thing and it was bugging the crap out of me. In firefox, it appears that if you try to do some things when the escape key is pressed, it continues processing the escape key which then cancels whatever you were trying to do. Alert works fine. But in my case, I wanted to go back in the history which did not work. Finally figured out that I had to force the propagation of the event to stop as shown below...

if (keyCode == 27)
{
    history.back();

    if (window.event)
    {
        // IE works fine anyways so this isn't really needed
        e.cancelBubble = true;
        e.returnValue = false;
    }
    else if (e.stopPropagation)
    {
        // In firefox, this is what keeps the escape key from canceling the history.back()
        e.stopPropagation();
        e.preventDefault();
    }

    return (false);
}
8

To explain where other answers haven't; the problem is your use of keypress.

Perhaps the event is just mis-named but keypress is defined to fire when when an actualcharacteris being inserted. I.e. text.
Whereas what you want is keydown/keyup, which fires whenever (before or after, respectively) the user depresses akey. I.e. those things on the keyboard.

The difference appears here because esc is a control character (literally 'non-printing character') and so doesn't write any text, thus not even firing keypress.
enter is weird, because even though you are using it as a control character (i.e. to control the UI), it is still inserting a new-line character, which will fire keypress.

Source: quirksmode

1
  • 1
    Kudos for reading the spec! This should be the accepted answer for sure :)
    – DylanYoung
    Commented May 10, 2018 at 14:21
7

To get the hex code for all the characters: http://asciitable.com/

3
  • 2
    I was gonna say..... I hate that this site is at the top of the search results because it's so damn ugly, but it does convey the necessary information.
    – mpen
    Commented Jul 21, 2009 at 17:29
  • 1
    Note that depending on event and browser, key codes do not always match ascii tables.
    – Alan H.
    Commented Jan 31, 2011 at 23:46
  • 2
    downvote: doesn't answer the question, doesn't even address the question, hex has nothing to do with the question and OP already demonstrated knowledge of esc == 27.
    – Jeremy
    Commented May 31, 2012 at 6:12
6

A robust Javascript library for capturing keyboard input and key combinations entered. It has no dependencies.

http://jaywcjlove.github.io/hotkeys/

hotkeys('enter,esc', function(event,handler){
    switch(handler.key){
        case "enter":$('.save').click();break;
        case "esc":$('.cancel').click();break;
    }
});

hotkeys understands the following modifiers: ,shiftoptionaltctrlcontrolcommand, and .

The following special keys can be used for shortcuts:backspacetab,clear,enter,return,esc,escape,space,up,down,left,right,home,end,pageup,pagedown,del,delete andf1 throughf19.

5

I have always used keyup and e.which to catch escape key.

5

I know this question is asking about jquery, but for those people using jqueryui, there are constants for many of the keycodes:

$.ui.keyCode.ESCAPE

http://api.jqueryui.com/jQuery.ui.keyCode/

2
$(document).on('keydown', function(event) {
   if (event.key == "Escape") {
       alert('Esc key pressed.');
   }
});
1
  • 1
    It's better to include an explanation instead of just code in your answer. Commented Mar 10, 2021 at 23:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.