KeyboardEvent Value (keyCodes, metaKey, etc)

When a KeyboardEvent fires, you can test which key was pressed because that event contains information you can write logic against.

document.addEventListener("keydown", function(event) {
  console.log(event.which);
}

For example, by pressing "a", you'll get 65. Apparently it's best to write logic against which, as keyCode and charCode are complicated:

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

And:

In a keypress event, the Unicode value of the key pressed is stored in either the keyCode or charCode property, never both. If the key pressed generates a character (e.g. 'a'), charCode is set to the code of that character, respecting the letter case. (i.e. charCode takes into account whether the shift key is held down). Otherwise, the code of the pressed key is stored in keyCode.

Tester Tool

See the Pen event.keyCode tester by Chris Coyier (@chriscoyier) on CodePen.

Table of Values

Key Code
backspace 8
tab 9
enter 13
shift 16
ctrl 17
alt 18
pause/break 19
caps lock 20
escape 27
(space) 32
page up 33
page down 34
end 35
home 36
left arrow 37
up arrow 38
right arrow 39
down arrow 40
insert 45
delete 46
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
a 65
b 66
c 67
d 68
Key Code
e 69
f 70
g 71
h 72
i 73
j 74
k 75
l 76
m 77
n 78
o 79
p 80
q 81
r 82
s 83
t 84
u 85
v 86
w 87
x 88
y 89
z 90
left window key 91
right window key 92
select key 93
numpad 0 96
numpad 1 97
numpad 2 98
numpad 3 99
numpad 4 100
numpad 5 101
numpad 6 102
numpad 7 103
Key Code
numpad 8 104
numpad 9 105
multiply 106
add 107
subtract 109
decimal point 110
divide 111
f1 112
f2 113
f3 114
f4 115
f5 116
f6 117
f7 118
f8 119
f9 120
f10 121
f11 122
f12 123
num lock 144
scroll lock 145
semi-colon 186
equal sign 187
comma 188
dash 189
period 190
forward slash 191
grave accent 192
open bracket 219
back slash 220
close braket 221
single quote 222

Comments

  1. User Avatar
    Hugo
    Permalink to comment#

    Great tip Chris, thanks for sharing !

    I never figured it is that simple to know keyCodes with jQuery.

  2. User Avatar
    John Jimenez
    Permalink to comment#

    Here is a decent article (a little out of date) about keycode support and the events that trigger.
    I am not affiliated with the link at all, just something I came across the other day and it happens to work here as well.
    http://unixpapa.com/js/key.html

  3. User Avatar
    JohnMotylJr
    Permalink to comment#

    Dang, im still using this:

    var code = (e.keyCode ? e.keyCode : e.which);
    • User Avatar
      Chris
      Permalink to comment#

      I still use that and always will until every browser uses the same property! Which will most likely never happen so I’d keep using it! I mean half these morons on here saying “Never knew it was that easy with jQuery” they must not know jQuery is a library of JavaScript -_- old developers will always out due all these newcomers, “jQuery” programmers. They make me laugh!

    • User Avatar
      spyter
      Permalink to comment#

      var code = e.keyCode || e.which; //is a shorter/cleaner version of what you have

    • User Avatar
      J G
      Permalink to comment#

      @spyter: just know that if e.keyCode === 0, then it will be falsey and fall through to e.which (which may not be a problem, but is a possibility)

  4. User Avatar
    James Larsson
    Permalink to comment#

    I found that the Apple command key is 224, which is not on this list.

  5. User Avatar
    saurabh
    Permalink to comment#

    i want alt+q =keycode??

    • User Avatar
      Mottie
      Permalink to comment#

      To detect that you’d need to look at the altKey value:

      if (event.altKey && event.which === 81) {
          // alt-q being used
      }
    • User Avatar
      zixuan
      Permalink to comment#

      i want alt+g =keycode??

  6. User Avatar
    Mottie
    Permalink to comment#

    @chriscoyier The table seems to be missing “space” with a event.which value of 32 :)

  7. User Avatar
    Crystal
    Permalink to comment#

    What about the key codes for other languages?

  8. User Avatar
    Veronica
    Permalink to comment#

    Just found out that, for event.which, only in FF, backspace is 8, and the arrow keys are 0. In Chrome, it doesn’t set a value for either.

    • User Avatar
      Aidan
      Permalink to comment#

      You are using element.onkeypress, to get the arrow keys you use element.onkeydown .

  9. User Avatar
    Ali.MD
    Permalink to comment#

    Thank you for exact copy paste and don’t read even once !
    I mean: ‘close braket’ just for fun ;)

  10. User Avatar
    Ali.MD
    Permalink to comment#

    Please also add these:
    NUM_LOCK_MAC: 12,
    F13: 124,
    F14: 125,
    F15: 126,
    F16: 127,
    F17: 128,
    F18: 129,
    F19: 130,

  11. User Avatar
    Strateji oyunu
    Permalink to comment#

    I wanting alt+q = keycode?

  12. User Avatar
    Ben Zörb
    Permalink to comment#

    There are some conflicting keycodes which belong to two characters when using keyup or keydown:
    188 , <
    190 . >
    191 / ?
    192 ` ~
    219 [ {
    220 \ |
    221 ] }
    222 ‘ “

  13. User Avatar
    Bhumi
    Permalink to comment#

    I have tried following but not working

    var DisableArrowKeys = function(e){
       if(e.keyCode == 40){
                    return false;
       }
       if(e.keyCode == 39){
                    return false;
        }
        return true;
    }
    $("#id").bind("keyup change", DisableArrowKeys);
    $("#id").bind("keydown change", DisableArrowKeys);
    
    • User Avatar
      sreeee
      Permalink to comment#
      $('#id').bind('keydown', function(e){
          if(e.keyCode == '39' || e.keyCode == '40'){
              e.preventDefault();
          }
      });
      

      this will help you i think

    • User Avatar
      amit
      Permalink to comment#

      google transliteration Api use, but keypress use . but i have not code for keypress,please give help google api with keypress use

    • User Avatar
      zixuan
      Permalink to comment#

      71: g

      the alt+g:
      18: alt
      have a alt at down and g at down.

  14. User Avatar
    Albert Straub
    Permalink to comment#

    How do you determine a capital letter from a lower-case letter?

    • User Avatar
      Carl Dolerado
      Permalink to comment#

      You cannot tell the difference between capitals and lower case as keycode handles the key being pressed so to it there is no difference between a capital and lower case same as there is no difference between 0 and ).

  15. User Avatar
    Marc
    Permalink to comment#

    Firefox 15+ returns 173 instead of 189 for dash. jQuery’s event.which does not normalize this. Previous versions returned 109.

  16. User Avatar
    Marc
    Permalink to comment#

    This list is quite good, also pointing out inconsistencies:
    http://www.javascripter.net/faq/keycodes.htm

    186, 187 and 189 from the above list are not safe to use.

  17. User Avatar
    kenny
    Permalink to comment#

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

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

    hotkeys('ctrl+a,ctrl+b,r,f', function(event,handler){
        switch(handler.key){
            case "ctrl+a":alert('you pressed ctrl+a!');break;
            case "ctrl+b":alert('you pressed ctrl+b!');break;
            case "r":alert('you pressed r!');break;
            case "f":alert('you pressed f!');break;
        }
    });
    

    hotkeys understands the following modifiers: , shift, option, , alt, ctrl, control, command, and .

    The following special keys can be used for shortcuts: backspace, tab, clear, enter, return, esc, escape, space, up, down, left, right, home, end, pageup, pagedown, del, delete and f1 through f19.

  18. User Avatar
    Sharkes Monken
    Permalink to comment#

    Thank god! Great article been searching for it finally now i can identify the Keyboard codes with “KeyCode” method :) Good Job

  19. User Avatar
    Muhammad Yasir
    Permalink to comment#

    Great post

  20. User Avatar
    Sven
    Permalink to comment#

    Hello dear people, I mod games but I still haven’t found out what to put in an INI file for the keybinding of Arrow Up and Arrow Down.
    If someone can help me I would be happy to hear from you.
    Sven

  21. User Avatar
    Mottie

    ThecharCode, keyCode and which are being deprecated. They will soon be replaced by event.key which will return named keys:

    document.querySelector('input').addEventListener('keydown', function(event) {
      console.log(event.key);
    });
    

    So If you type in “Hello World”, this will end up in the console:

    Shift
    H
    e
    l
    l
    o
    
    Shift
    W
    o
    r
    l
    d
    

    The event.shiftKey will still be true for shifted characters, but there is a new method to check for modifier keys (shift, alt, altGr, ctlr, capsLock, meta, OS, etc.) named getModifierState:

    document.querySelector('input').addEventListener('keydown', function(event) {
        console.log(event.getModifierState());
    });
    

    Which will return values like this:

    Shift
    Alt
    AltGraph
    Control
    CapsLock
    Meta
    OS
    
  22. User Avatar
    Hrach

    Is there a reason the lowest keycode is 8, or is that just how it is for no reason what so ever.

  23. User Avatar
    Mohamed Hussain S H

    In Codepen shared in the article, event.which is not respecting the case, always gives me 65 when i press lowercase “a” or uppercase “A”. am I understand something wrong here?

    • User Avatar
      Mottie

      The codes within a keypress event will provide the proper ASCII character equivalents of the typed character. Try this demo.

      Note that the keypress does not contain a value for some special keys, like the arrows, insert, delete, home, pageUp/Down, etc.

  24. User Avatar
    Paco
    Permalink to comment#

    I wanting ctrlKey+c = keycode?

    y try these :

    only: function(event) {

        if( event.ctrlKey && event.which === 86)  {
                        event.preventDefault();
           }
     }
    

    but dont go :( … do you have another idea :)

    THX

  25. User Avatar
    Ramana
    Permalink to comment#

    How to get the Ctrl+space event?

  26. User Avatar
    Ajin
    Permalink to comment#

    Any one know when press 1 then the input box displays I(Uppercase of I(i))

  27. User Avatar
    Mottie
    Permalink to comment#

    @chriscoyier This post will need to be updated soon… most browsers now support the new keyboard events, including getModifierState().

  28. User Avatar
    Paolo
    Permalink to comment#

    I get inconsistent evt.which values when listening to keydown on Safari 9, expecially for symbols like +, -, etc..

    I get reasonable values (ascii values) if I listen to keypress.

    I need to stick with keydown for non-character keys like arrows.

    Furthermore keypress is annoying if you don’t want the event being triggered multiple times if the user holds the key down.

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag