Detecting Arrow Keys With JavaScript

This topic is 1614 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I have ran into a bit of a problem when attempting to detect which arrow keys some one has presses.

No matter what I use, I end up with NULL being returned for arrow keys - here is the bit of the code were I get what key is presses.

function key(){
// This works for keys, but not arrows
document.onkeypress=function(e){
var e=window.event || e
alert("CharCode value: " + e.charCode + "\nCharacter: " + String.fromCharCode(e.charCode) )
}
// This returns NULL for everything
document.onkeydown=function(e){
var e=window.event || e
alert("CharCode value: " + e.charCode + "\nCharacter: " + String.fromCharCode(e.charCode) )
}
}


.

Here is a working code example I threw together to demonstrate the issue. It is not complete, but it gets the job done to point out my issue ...

.

<html>
<center>
<canvas id="x" width="500" height="500" style="border:1px solid #000000;"></canvas>
</center>
<script>
var c=document.getElementById("x");
var ctx=c.getContext("2d");
var FPS = 30;
setInterval(function(){
update();
draw();
},1000/FPS);
function update(){
key();
}
function draw(){
ctx.clearRect(0,0,500,500);
}
function key(){
// This works for keys, but not arrows
document.onkeypress=function(e){
var e=window.event || e
alert("** Test 1 **  \nCharCode value: " + e.charCode + "\nCharacter: " + String.fromCharCode(e.charCode) )
}
// This returns NULL for everything
document.onkeydown=function(e){
var e=window.event || e
alert("** Test 2 ** \nCharCode value: " + e.charCode + "\nCharacter: " + String.fromCharCode(e.charCode) )
}
}
</script>
</html>

Edited by Shippou

Share on other sites

arrow keys are not triggered by onkeypress, try onkeydown

keycodes are:

• left = 37
• up = 38
• right = 39
• down = 40

Also rename e.charCode with e.keyCode for it to return the proper values. Either way, I suggest you use console.log instead of alert, makes things easier

Edited by hatenames