How to find out what character key is pressed?

JavascriptDom EventsKeypress

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

"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/>

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

**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>

Solution 7 - Javascript

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>

Solution 8 - Javascript

document.onkeypress = function(event){
    alert(event.key)
}

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
QuestionxXxView Question on Stackoverflow
Solution 1 - JavascriptCoyodView Answer on Stackoverflow
Solution 2 - JavascriptTim DownView Answer on Stackoverflow
Solution 3 - JavascriptGiboltView Answer on Stackoverflow
Solution 4 - JavascriptlewdevView Answer on Stackoverflow
Solution 5 - JavascriptJCassoView Answer on Stackoverflow
Solution 6 - Javascriptkki3908050View Answer on Stackoverflow
Solution 7 - Javascriptdipole_momentView Answer on Stackoverflow
Solution 8 - JavascriptgomozorView Answer on Stackoverflow