I am looking for a way to execute a javascript function when a specific key is pressed, for example pressing the down key will result in function down()
and the left key will execute function left()
. Is this possible preferably with javascript? I could use jquery, but I prefer javascript. Thanks!
Asked
Active
Viewed 1,171 times
0

Thomas Lai
- 317
- 1
- 6
- 15
2 Answers
2
Sure it's possible:
document.addEventListener('keydown', function(e){
if(e.keyCode === 40) {
down();
} else if(e.keyCode === 38) {
up();
}
},false);

Community
- 1
- 1

bfavaretto
- 71,580
- 16
- 111
- 150
-
so is `down()` another function? – Thomas Lai Feb 15 '13 at 01:44
-
Yes, I was assuming you already had it. But it doesn't have to be, you can do whatever you want to do right inside the conditionals, instead of calling `up()` or `down()`. – bfavaretto Feb 15 '13 at 01:46
-
ok, thanks, sorry but I'm a beginner at javascript – Thomas Lai Feb 15 '13 at 01:48
1
bfavaretto's answer is good, but it won't support all the browsers. Try this:
document.addEventListener('keydown', function(event){
event = event || window.event;
var keycode = event.charCode || event.keyCode;
if(keycode == 37)
left();
if(keycode == 39)
right();
if(keycode == 38)
up();
if(keycode == 40)
down();
});

Tom
- 4,422
- 3
- 24
- 36