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?
Keycode 13 is the Enter key.
Note: The keyCode property is deprecated. Use the key property instead.
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.
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
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 implementedKeyboardEvent.keyIdentifier
, which was defined in a draft specification but not the final spec.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With