0

I want to run a method whenever the ESC button gets clicked. In the onkeypress Event documentation I read that i will have to use keydown

Note: The onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC) in all browsers. To detect only whether the user has pressed a key, use the onkeydown event instead, because it works for all keys.

I managed to write a working example:

document.onkeydown = function (e) {
  if (document.getElementById("fullscreen") !== null) {
    var key = e.which || e.keyCode;
    if (key === 27) {
      alert(1);
    }
  }
}
<div id="fullscreen">test</div>

The event listeners in our project have a different pattern, so I tried rewrite it in the same pattern but the code isn't reacting on the key press.

document.getElementById("fullscreen").addEventListener("keydown",
  function (e) {
    var key = e.which || e.keyCode;
    if (key === 27) {
      alert(1);
    }
  });
<div id="fullscreen">test</div>

Why isn't the second code snippet reacting on the key press like the first snippet?

  • 1
    `div` elements don't naturally gain focus, which is needed to trigger key events. Add `tabindex` attribute to `#fullscreen` to make it focusable. – Teemu Aug 31 '18 at 09:49
  • 2
    Possible duplicate of [Capture key press (or keydown) event on DIV element](https://stackoverflow.com/questions/3149362/capture-key-press-or-keydown-event-on-div-element) – Luca Kiebel Aug 31 '18 at 09:53

0 Answers0