How to find out what character key is pressed?

Viewed 282942

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

10 Answers

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

Detecting Keyboard press in JavaScript:

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

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

Related