I understand that this might seem like a grim answer and I apologise if it is.
I have struggled with this issue a few weeks ago and eventually gave up on it.
Countless hours of trying to get the arrow keys on the iPad to fire the onkeydown
event did seem to work at all, it was like they weren't even being pressed.
A good alternative for a game (or something like that) is to use the WSAD
keys, this was what I did.
The codes for the WSAD
keys are:
w: 87,
s: 83,
a: 65,
d: 68
This is how you would normally detect when the WSAD
keys have been pressed:
$(document).on("keydown", function(event) {
if (event.which == 87) {
// W key Has Been Pressed
} else if (event.which == 83) {
// S key Has Been Pressed
} else if (event.which == 65) {
// A key Has Been Pressed
} else if (event.which == 68) {
// D key Has Been Pressed
}
// prevent the default action
// event.preventDefault(); // This is optional.
});
The codes for the arrow keys are:
up: 38,
down: 40,
left: 37,
right: 39
This is how you would normally detect when the arrows keys have been pressed:
$(document).on("keydown", function(event) {
if (event.which == 37) {
// Left Arrow Has Been Pressed
} else if (event.which == 38) {
// Up Arrow Has Been Pressed
} else if (event.which == 39) {
// Right Arrow Has Been Pressed
} else if (event.which == 40) {
// Down Arrow Has Been Pressed
}
// prevent the default action
event.preventDefault();
});
NOTE: you can only use the onkeydown
event to check if the the arrow keys have been pressed.
You can also use var key = event.keyCode ? event.keyCode : event.which;
Quoting Peter Darmis:
Versions of Opera before 10.50 messes up by returning non-zero event.which
values for four special keys (Insert, Delete, Home and End), meaning using event.keyCode
may be more "fail safe" across older browsers.
Source
Quoting the jQuery api:
The event.which property normalizes event.keyCode
and event.charCode
. It is recommended to watch event.which
for keyboard key input. For more detail, read about event.charCode
on the MDN.
Source
Good luck, and all the best.