event.charCode always returning 0

html, javascript

Solution

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

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

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

Problem

I have a page where I need to capture input from a user after they click on a part of the page (a div). Here's 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 it in action: http://jsfiddle.net/WRwBF/ It took me the longest time to get this far because FireFox doesn't by default allow a div to "have focus." Eventually I found out that setting the tabindex for the div allows it to be in focus and the onkeydown event works. My problem now is that when I click in the div and press a key, the value "0" is returned regardless of what key is pressed. Why would this be happening, and how can I fix it? I would very much appreciate any guidance you might be able to give!

Original source