Event.charCode always returns 0

I have a page where I need to capture input from the user after they click on parts of the page (div). Here is my code:

<html> <body> <div style="background-color: lightpink" onkeydown="onkeydown1(event)" tabindex="-1"> click me, then press a key </div> <script type="text/javascript"> function onkeydown1(event) { alert(event.charCode); } </script> </body> </html> 

See in action: http://jsfiddle.net/WRwBF/

It took me the longest time to go that far, because FireFox does not allow the div to “have focus” by default. In the end, I found out that setting tabindex for the div allows it to be in focus, and the onkeydown event works.

Now my problem is that when I click on the div and press the key, the value "0" is returned no matter which key is pressed. Why is this happening, and how can I fix it?

I would really appreciate any advice you could give!

+6
source share
3 answers

Read http://unixpapa.com/js/key.html .

Summary: using the keypress event is the only way to get reliable information about the entered character. The following will be good enough for you to get a character typed in most situations:

 var charCode = (typeof event.which == "undefined") ? event.keyCode : event.which; alert("Character typed: " + String.fromCharCode(charCode)); 
+4
source

Use event.keyCode or event.which (depending on browser) instead

0
source

You have focus with the tabindex property, and you can use it to tab, but there is no interface for the div to get the key event.

You get those from the text inputs and the window itself.

0
source

Source: https://habr.com/ru/post/918845/


All Articles