9

I know that when working with JavaScript or jQuery. I can add an event listener on an object to call a function when a key is pressed.

However, if the function is launched from HTML, as in the following example:

function callMyFunction (importantothervalue) {
  //How can I get the keycode?
}
<textarea onkeyup="callMyFunction(1);"></textarea>
<textarea onkeyup="callMyFunction(2);"></textarea>
<textarea onkeyup="callMyFunction(3);"></textarea>

Is there any way to retrieve the key code from this context? Or do I always need to make an event handler if I want to get the key code?

Is there any way for me to include importantothervalue in the resulting function call without encoding the information in the id or class attribute and extracting it from there?

Mamun
  • 66,969
  • 9
  • 47
  • 59
azoundria
  • 940
  • 1
  • 8
  • 24

1 Answers1

10

Use event.key (or event.code)

You can pass event to the function from which you can access the property key.

I would recommend you to see the documentation for KeyboardEvent.key and KeyboardEvent.code

Beware of the old keyCode

You should avoid using this if possible; it's been deprecated for some time. Instead, you should use KeyboardEvent.code, if it's implemented. Unfortunately, some browsers still don't have it, so you'll have to be careful to make sure you use one which is supported on all target browsers. Google Chrome and Safari have implemented KeyboardEvent.keyIdentifier, which was defined in a draft specification but not the final spec.

Example

function callMyFunction (e, importantothervalue) {
  console.log(e.key); // ex: "j"
  console.log(e.code); // ex: "KeyJ"
  console.log(importantothervalue)
}
<textarea onkeyup="callMyFunction(event, 1);"></textarea>
<textarea onkeyup="callMyFunction(event, 2);"></textarea>
<textarea onkeyup="callMyFunction(event, 3);"></textarea>
coolaj86
  • 74,004
  • 20
  • 105
  • 125
Mamun
  • 66,969
  • 9
  • 47
  • 59