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

1

11

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?

Antione answered 14/1, 2019 at 6:39 Comment(4)
Are you able to alter the HTML handler?Methylamine
That was a very fast reply, but I'm not sure what that means. I can put anything in the onkeyup attribute. I would like to pass additional parameters with the onkeyup.Antione
what you can do is also pass event with other arguments like <textarea onkeyup="callMyFunction(event, 3);"></textarea> and in method you can access key code by event.keyCodeBodnar
developer.mozilla.org/en-US/docs/Web/Events/keyupNeighbor
P
13

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

But I would recommend you to see the documentation before using KeyboardEvent.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.

function callMyFunction (e, importantothervalue) {
  console.log(e.code);
  console.log(importantothervalue)
}
<textarea onkeyup="callMyFunction(event, 1);"></textarea>
<textarea onkeyup="callMyFunction(event, 2);"></textarea>
<textarea onkeyup="callMyFunction(event, 3);"></textarea>
Parke answered 14/1, 2019 at 6:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.