Reputation: 28384
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!
Upvotes: 8
Views: 8278
Reputation: 324567
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));
Upvotes: 7
Reputation: 104770
You got focus with the tabindex property, and you can tab to it, but there is no interface for a div to receive a key event.
You get those from text inputs and the window itself.
Upvotes: 0
Reputation: 11342
Use event.keyCode
or event.which
(depending on browser) instead
Upvotes: 1