How to find out what character key is pressed?
Asked Answered
I

10

159

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

Idioblast answered 4/12, 2009 at 12:17 Comment(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?Thunell
event.key will directly give you the pressed charHolst
I
191

"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/>
Indoxyl answered 4/12, 2009 at 12:36 Comment(8)
this works ok for alphabetic chars, but what about dots/brakets and other typogtaphic symbols?Chrome
@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.Hick
e.which is deprecated. Use e.key instead, as in if(e.key == 'z')Dodge
@aljgom, e.key still doesn't have full browser support.Argolis
Doesn't work for symbols that you have to press shift to make, like !Incubator
@AndyMercer key is now supported by all major browsers: developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/…Lavonna
The keypress event seems to be deprecated w3.org/TR/DOM-Level-3-Events/#event-type-keypressDuwe
the keyCode for ArrowLeft is 37, which is % symbol. So this conversion doesn't seem to be fully reliablePrescription
H
52

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

Holst answered 5/9, 2017 at 18:3 Comment(3)
Is this for node.js?Koheleth
No, node just means any DOM element. If you had Node.js connecting to a UI, I suppose it would workHolst
keydown for some mobile device doesn't work it return undefineBugle
H
43

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.

Hick answered 4/12, 2009 at 12:41 Comment(0)
J
17

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.

Joel answered 21/8, 2018 at 19:49 Comment(2)
Here's another similar site but with a few additional options: keyjs.devReverso
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!Beeline
S
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');
  }
}
Scotch answered 4/12, 2009 at 12:31 Comment(0)
M
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>
Mun answered 8/12, 2014 at 12:31 Comment(1)
Isn't this a near-exact duplicate of @Coyod's 2009 answer?Sanitation
H
2

Detecting Keyboard press in JavaScript:

document.addEventListener(
  "keydown",
  function(event) {
    console.log(event.key);
  },
);
Hung answered 19/6, 2022 at 23:29 Comment(0)
D
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>
Dylandylana answered 13/11, 2015 at 13:47 Comment(1)
Uncaught TypeError: Mousetrap.record is not a function at recordSequence (****.html:12) at HTMLButtonElement.onclick (****.html:20)Winnipegosis
F
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

Foist answered 3/8, 2022 at 6:40 Comment(2)
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.Aguilar
@Aguilar 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.Deventer
D
-2
document.onkeypress = function(event){
    alert(event.key)
}
Donatello answered 7/3, 2018 at 19:10 Comment(2)
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. thanksPompon
easy to vote, I guess you bettter try this snippet on your own :) title is pretty common by the wayDonatello

© 2022 - 2024 — McMap. All rights reserved.