Detecting Arrow Keys With JavaScript

Started by
0 comments, last by hatenames 10 years, 8 months ago

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>

I cannot remember the books I've read any more than the meals I have eaten; even so, they have made me.

~ Ralph Waldo Emerson

Advertisement

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

This topic is closed to new replies.

Advertisement