Which keycode for escape key with jQuery

JavascriptJquery

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

Try with the keyup event:

$(document).on('keyup', function(e) {
  if (e.key == "Enter") $('.save').click();
  if (e.key == "Escape") $('.cancel').click();
});

Solution 2 - Javascript

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.

Solution 3 - Javascript

(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/)

Solution 4 - Javascript

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

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

Solution 5 - Javascript

27 is the code for the escape key. :)

Solution 6 - Javascript

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

Solution 7 - Javascript

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

Solution 8 - Javascript

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

Solution 9 - Javascript

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';
    }

});

Solution 10 - Javascript

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

Solution 11 - Javascript

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 actual character is being inserted. I.e. text.
Whereas what you want is keydown/keyup, which fires whenever (before or after, respectively) the user depresses a key. 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

Solution 12 - Javascript

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

Solution 13 - Javascript

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.

Solution 14 - Javascript

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

Solution 15 - Javascript

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/

Solution 16 - Javascript

$(document).on('keydown', function(event) {
   if (event.key == "Escape") {
       alert('Esc key pressed.');
   }
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShishantView Question on Stackoverflow
Solution 1 - JavascriptChristian C. SalvadóView Answer on Stackoverflow
Solution 2 - JavascriptSeth Petry-JohnsonView Answer on Stackoverflow
Solution 3 - JavascriptJordan BroughView Answer on Stackoverflow
Solution 4 - JavascriptHanzelView Answer on Stackoverflow
Solution 5 - JavascriptSaltyView Answer on Stackoverflow
Solution 6 - JavascriptShital ShahView Answer on Stackoverflow
Solution 7 - JavascriptS. Ferit ArslanView Answer on Stackoverflow
Solution 8 - JavascriptaugView Answer on Stackoverflow
Solution 9 - JavascriptEric HerlitzView Answer on Stackoverflow
Solution 10 - JavascriptBilly BuergerView Answer on Stackoverflow
Solution 11 - JavascriptHashbrownView Answer on Stackoverflow
Solution 12 - JavascriptJulienView Answer on Stackoverflow
Solution 13 - Javascript小弟调调View Answer on Stackoverflow
Solution 14 - JavascriptDalius IView Answer on Stackoverflow
Solution 15 - JavascriptTroy GrosfieldView Answer on Stackoverflow
Solution 16 - JavascriptKazbek KadalashviliView Answer on Stackoverflow