1

Whether the fact that a lot of features have been deprecated or are not part of the current standard for the KeyboardEvent object class. Was just wondering why whenever I press either shift or esc. Non of the keys show up on my console for Chrome or Mozilla.

document.addEventListener("keypress", (e) => {
    console.log(e.keyCode);
    console.log(e.key);
    console.log(e.code);
    console.log(e.shiftKey);
});

Browser Consoles used

  • "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0"
  • "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"
  • [Web Inspector] "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Safari/604.1.38"

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

A. Tran
  • 333
  • 1
  • 5
  • 13
  • 2
    The `keypress` event does not trigger for each key, only when it corresponds to a character (or backspace). Use `keydown` or `keyup` instead. – trincot Oct 22 '17 at 20:16

1 Answers1

9

keypress is only triggered when a printable character is pressed. For all keys, you need to work with keyup or keydown.

From MDN:

keypress

The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt, Shift, Ctrl, or Meta.

document.addEventListener("keydown", (e) => {
    console.log(e.keyCode);
    console.log(e.key);
    console.log(e.code);
    console.log(e.shiftKey);
});
<h1>Click into this area and then press ESC</h1>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71