Get the pressed key in JavaScript

See here for the original answer.

One way to do this that's even shorter than the other answers:

document.onkeydown = (e) => console.log(e.key);

This uses an inline function to further reduce the length of the answer by zer00ne.

If you are more interested in form validation than just logging to the console, you can also do something along the lines of the following:

function alphaOnly(event) {
  let key = event.keyCode;
  return ((key >= 65 && key <= 90) || key == 8);
};

Tags

  1. javascript (Private)
  2. keypress (Private)
  3. event (Private)
  4. event-listener (Private)
  5. stack-overflow (Private)
  6. answer (Private)