Sign in to follow this  
RLS0812

Detecting Arrow Keys With JavaScript

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 this post


Link to post
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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this