Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect the KeyboardEvent for the escape key? [duplicate]

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

like image 213
A. Tran Avatar asked Dec 03 '25 18:12

A. Tran


1 Answers

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>
like image 196
Scott Marcus Avatar answered Dec 06 '25 09:12

Scott Marcus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!