156

I would like to find out what character key is pressed in a cross-browser compatible way in pure Javascript.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
xXx
  • 1,631
  • 2
  • 12
  • 5
  • 2
    Aren't all these answers for the question "what key _was_ pressed?" What if, as it's executing, javascript code wants to know if a key on the keyboard is currently held down? – mwardm Oct 07 '16 at 16:24
  • 5
    `event.key` will directly give you the pressed char – Gibolt Sep 05 '17 at 18:04

10 Answers10

188

"Clear" JavaScript:

function myKeyPress(e){
  var keynum;

  if(window.event) { // IE                  
    keynum = e.keyCode;
  } else if(e.which){ // Netscape/Firefox/Opera                 
    keynum = e.which;
  }

  alert(String.fromCharCode(keynum));
}
<input type="text" onkeypress="return myKeyPress(event)" />

JQuery:

$("input").keypress(function(event){
  alert(String.fromCharCode(event.which)); 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input/>
Lakshya Raj
  • 1,669
  • 3
  • 10
  • 34
Coyod
  • 2,656
  • 2
  • 18
  • 13
  • 8
    this works ok for alphabetic chars, but what about dots/brakets and other typogtaphic symbols? – VoVaVc Jan 24 '14 at 15:13
  • 7
    @VoVaVc: It works for those too. The crucial thing is using the `keypress` event, which gives you a character code, rather than `keyup` or `keydown` which give you a key code. – Tim Down Feb 09 '15 at 14:12
  • `e.which` is deprecated. Use `e.key` instead, as in `if(e.key == 'z')` – aljgom Apr 08 '17 at 18:09
  • 2
    @aljgom, `e.key` still doesn't have full browser support. – Kelderic Nov 29 '17 at 18:23
  • 1
    Doesn't work for symbols that you have to press shift to make, like ! – Curtis Aug 06 '18 at 04:54
  • 6
    @AndyMercer key is now supported by all major browsers: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key#Browser_compatibility – Ray Dec 23 '18 at 14:22
  • 2
    The keypress event seems to be deprecated https://www.w3.org/TR/DOM-Level-3-Events/#event-type-keypress – Zuabi Apr 24 '20 at 07:15
  • the `keyCode` for `ArrowLeft` is 37, which is `%` symbol. So this conversion doesn't seem to be fully reliable – 8bitjoey Apr 05 '23 at 09:14
49

More recent and much cleaner: use event.key. No more arbitrary number codes!

NOTE: The old properties (.keyCode and .which) are Deprecated.

node.addEventListener('keydown', function(event) {
    const key = event.key; // "a", "1", "Shift", etc.
});

If you want to make sure only single characters are entered, check key.length === 1, or that it is one of the characters you expect.

Mozilla Docs

Supported Browsers

Gibolt
  • 42,564
  • 15
  • 187
  • 127
42

There are a million duplicates of this question on here, but here goes again anyway:

document.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = evt.keyCode || evt.which;
    var charStr = String.fromCharCode(charCode);
    alert(charStr);
};

The best reference on key events I've seen is http://unixpapa.com/js/key.html.

Tim Down
  • 318,141
  • 75
  • 454
  • 536
16

Copy-paste this into your address-bar:

data:text/html,<body style=font:12vw' onkeyup="this.innerHTML=['key','keyCode','code'].map(k=>k+': '+event[k]).join`<br>`">Press a key

This is just 134 bytes of code to produce the key, keyCode, and code of the key you've just pressed. You can also save this as a bookmark so you can run it anytime.

<body style=font:8vw'
  onkeyup="this.innerHTML=['key','keyCode','code'].map(k=>k+': '+event[k]).join`<br>`"
  >Press a key

This works in "Run code snippet" as well.

Lewis Nakao
  • 7,079
  • 2
  • 26
  • 21
  • Here's another similar site but with a few additional options: https://keyjs.dev – Danziger Sep 27 '20 at 07:15
  • on chrome, xfce, italian keyboard, spanish layout, pressing "<" returns "/", which is the key which is there in english keyboard. Why?!? some chrome versions ago it was not that! – Paolo Benvenuto Nov 12 '21 at 17:40
3

Use this one:

function onKeyPress(evt){
  evt = (evt) ? evt : (window.event) ? event : null;
  if (evt)
  {
    var charCode = (evt.charCode) ? evt.charCode :((evt.keyCode) ? evt.keyCode :((evt.which) ? evt.which : 0));
    if (charCode == 13) 
        alert('User pressed Enter');
  }
}
JCasso
  • 5,423
  • 2
  • 28
  • 42
2
**check this out** 
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(document).keypress(function(e)
        {

            var keynum;
            if(window.event)
            { // IE                 
                keynum = e.keyCode;
            }
                else if(e.which)
                    { 
                    // Netscape/Firefox/Opera                   
                    keynum = e.which;
                    }
                    alert(String.fromCharCode(keynum));
                    var unicode=e.keyCode? e.keyCode : e.charCode;
                    alert(unicode);
        });
});  

</script>
</head>
<body>

<input type="text"></input>
</body>
</html>
kki3908050
  • 165
  • 2
  • 9
2

Detecting Keyboard press in JavaScript:

document.addEventListener(
  "keydown",
  function(event) {
    console.log(event.key);
  },
);
Saeed Zhiany
  • 2,051
  • 9
  • 30
  • 41
Bayram Binbir
  • 1,531
  • 11
  • 11
1

One of my favorite libraries to do this in a sophisticated way is Mousetrap.

It comes stocked with a variety of plugins, one of which is the record plugin which can identify a sequence of keys pressed.

Example:

<script>
    function recordSequence() {
        Mousetrap.record(function(sequence) {
            // sequence is an array like ['ctrl+k', 'c']
            alert('You pressed: ' + sequence.join(' '));
        });
    }
</script>


<button onclick="recordSequence()">Record</button>
dipole_moment
  • 5,266
  • 4
  • 39
  • 55
  • Uncaught TypeError: Mousetrap.record is not a function at recordSequence (****.html:12) at HTMLButtonElement.onclick (****.html:20) – Irrmich Jun 17 '20 at 09:18
0

BH

If you're trying to get the value in client side JavaScript via the DOM, then a reliable alternative I've found is to make an invisible <input> element, with an absolute position and (almost) no width, positioned underneath wherever you're typing, then when the user clicks or sets focus to whatever they're supposed to type on, call the focus() function on the input, and use the result from the oninput event to get the string entered into the input, and then get the first character from that string, or loop through it

(And make some exceptions for shift keys etc)

Then at the end of every event simply reset the value of the input to an empty string

Yeets
  • 107
  • 3
  • You should be able to add a `keydown` listener to `document` without needing to create an extra input element. This answer adds very little to the existing ones. – Matthias Aug 04 '22 at 20:09
  • @Matthias and what is the cross browser, reliable way to get the Unicode character pressed by the user with any other method than this one? The .key property isn't supported on many mobile devices. Even charCode from keypress is no longer supported. Even keyCode from keydown etc is no longer supported, and only dealt with the key itself, not the Unicode char. – Yeets Aug 07 '22 at 14:04
-2
document.onkeypress = function(event){
    alert(event.key)
}
gomozor
  • 97
  • 6
  • 1
    two negative votes but now explaination why it is voted negative. I think it help when you comment what is the problem with this answer. thanks – MindRoasterMir Dec 14 '21 at 20:12
  • easy to vote, I guess you bettter try this snippet on your own :) title is pretty common by the way – gomozor Dec 15 '21 at 08:00