Jump to content
  • Advertisement
Sign in to follow this  
RLS0812

Detecting Arrow Keys With JavaScript

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

If you intended to correct an error in the post then please contact us.

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

Edited by hatenames

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!