Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the key code from onkeyup? [duplicate]

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?

like image 965
azoundria Avatar asked Jan 14 '19 06:01

azoundria


People also ask

What is e keyCode === 13?

Keycode 13 is the Enter key.

What can I use instead of keyCode?

Note: The keyCode property is deprecated. Use the key property instead.

What is the difference between keyCode and charCode?

keyCode: Returns the Unicode value of a non-character key in a keypress event or any key in any other type of keyboard event. event. charCode: Returns the Unicode value of a character key pressed during a keypress event.


1 Answers

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>
like image 81
Mamun Avatar answered Sep 24 '22 20:09

Mamun