2

I'm trying to make a script to detect if a certain key is being pressed, but the only reasonable thing I could think of was this.

onkeydown('F12'){
    myFunction()
}

How would I do this? Thanks!

Westlenando
  • 88
  • 1
  • 8
  • 3
    Does this answer your question? [Simplest way to detect keypresses in javascript](https://stackoverflow.com/questions/16089421/simplest-way-to-detect-keypresses-in-javascript) – Brian McCutchon Jun 11 '20 at 00:47

4 Answers4

1

Add an event listener for the "keydown" (or "keyup") action. To get the specific key that was pressed use "event.key".

document.addEventListener("keydown", function(e){
    var key = e.key
})
PeterSH
  • 425
  • 3
  • 14
1

using keyCode you can get the specific key. This example works if you press enter keyword (code 13). Check this out: https://keycode.info/

document.addEventListener("keypress", function(event) {
  if (event.keyCode == 13) {
   console.log('Hello world');
  }
});
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
  • 1
    Both `keypress` and `e.keyCode` are deprecated. `keydown` and `e.key` or `e.code` should be used instead. Also, check out this other tool: https://keyjs.dev – Danziger Sep 27 '20 at 07:26
1

You should listen for the keydown event and check its e.key property:

const KEY_HANDLERS = {
  F1: () => console.log('You pressed F1.'),
  ArrowUp: () => console.log('You pressed ↑.'),
  KeyA: () => console.log('You pressed A.'),
};

document.addEventListener('keydown', (e) => {
    e.preventDefault();

    const handler = KEY_HANDLERS[e.code];
    
    if (handler) {
      handler();
      return;
    }
    
    console.log('Pressed a key without a handler.')
});

If you need to check KeyboardEvent's properties values such as e.key, e.code, e.which or e.keyCode, you can use https://keyjs.dev:

Key.js \ JavaScript KeyboardEvent's key codes & key identifiers

Disclaimer: I'm the author.

Danziger
  • 19,628
  • 4
  • 53
  • 83
0

Maybe this is what you are looking for:

var inputForm = document.getElementById("taskInput");

inputForm.addEventListener('keydown', function(event) {
 console.log("You are pressing this key :", String.fromCharCode(event.keyCode));
});
<input type="text" id="taskInput"/>
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
  • `e.keyCode` is deprecated. You should be using `e.key` or `e.code`, especially considering that you are using the `keyCode` to get the character using `String.fromCharCode`, which you would get straight away from `e.key`, including special values such as `Space, Escape, ArrowUp, ArrowRight, Delete...` – Danziger Sep 27 '20 at 07:28