141

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

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
xXx
  • 1,481
  • 2
  • 11
  • 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

8 Answers8

180

"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,094
  • 4
  • 20
Coyod
  • 2,558
  • 2
  • 17
  • 13
  • 6
    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. – Andy Mercer 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
  • 1
    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
41

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
  • 306,503
  • 71
  • 443
  • 520
38

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
  • 33,561
  • 12
  • 157
  • 107
15

Try:

<table>
  <tr>
    <td>Key:</td>
    <td id="key"></td>
  </tr>
  <tr>
    <td>Key Code:</td>
    <td id="keyCode"></td>
  </tr>
  <tr>
    <td>Event Code:</td>
    <td id="eventCode"></td>
  </tr>
</table>
<script type="text/javascript">
  window.addEventListener("keydown", function(e) {
    //tested in IE/Chrome/Firefox
    document.getElementById("key").innerHTML = e.key;
    document.getElementById("keyCode").innerHTML = e.keyCode;
    document.getElementById("eventCode").innerHTML = e.code;
  })
</script>

*Note: this works in "Run code snippet"

This website does the same as my code above: Keycode.info

Alexander Nied
  • 11,309
  • 4
  • 26
  • 41
lewdev
  • 6,233
  • 2
  • 27
  • 21
2

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,293
  • 2
  • 27
  • 40
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
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
  • 4,266
  • 2
  • 38
  • 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
-2
document.onkeypress = function(event){
    alert(event.key)
}
gomozor
  • 97
  • 5
  • 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