I have a div with an id of bottom_arrow
and I want to use my keyboard arrows left/right to move the div left and right 100px. How can I do this?
Asked
Active
Viewed 5,873 times
1

thenengah
- 42,557
- 33
- 113
- 157
-
in my own search I have found this http://atomicrobotdesign.com/blog/htmlcss/animate-a-random-bouncing-ball-with-the-canvas-tag/ – thenengah Dec 10 '10 at 01:59
-
Incidentally, just found a duplicate: http://stackoverflow.com/questions/4104158/jquery-keypress-left-right-navigation – Orbling Dec 10 '10 at 02:09
-
Nice example, though HTML5 ` – Orbling Dec 10 '10 at 02:11
3 Answers
5
As a rule keypress events go to an input or some control that has focus, if you need them generally on a page, which is a sometimes a little frowned upon due to removing standard behavior, then bind the keydown event to the whole document.
$('body').keydown(function(event) {
switch (event.keycode) {
case 37: // left arrow key
$('#bottom_arrow').animate({ 'left': '-=100' });
break;
case 39: // right arrow key
$('#bottom_arrow').animate({ 'left': '+=100' });
break;
}
});
I have used keydown
, rather than keypress
as a user would expect it to trigger whilst pressing the key.

Orbling
- 20,413
- 3
- 53
- 64
-
@Sam: Quite alright, bear in mind you will probably need to `position` the `` in a way in which altering the `left` position will have the desired effect.– Orbling Dec 10 '10 at 02:16
-
How should I style the div so I can move it with up and down arrows? – thenengah Dec 11 '10 at 20:58
-
@Sam: Up/Down are keycodes 38/40, use as with the above, but use the `top` css style. Make sure the element has `position: absolute;` or `position: relative;` if necessary. – Orbling Dec 11 '10 at 21:37
-
yeah, I meant to say left/right. I've tried the different positions but it hasn't done to much. – thenengah Dec 11 '10 at 21:43
-
@Sam: It is sometimes difficult to see what the issue is with these problems without seeing the HTML/CSS in question. Have you used the position attribute for the items you wish to move about? Post some code on your question and I'll have a look later. – Orbling Dec 11 '10 at 21:47
-
It didn't work for me because until I changed 'event.keycode' to 'event.keyCode' – Jones03 Jun 20 '14 at 03:54
0
$('body').keydown(function(event) {
switch (event.keycode) {
case 37: // left arrow key
$('#bottom_arrow').animate({ 'left': '-=100' });
break;
case 39: // right arrow key
$('#bottom_arrow').animate({ 'left': '+=100' });
break;
}
});

falsetru
- 357,413
- 63
- 732
- 636
0
According to Jquery documentation, use event.which instead.
$('body').keydown(function(event) {
switch (event.which) {
case 37: // left arrow key
$('#bottom_arrow').animate({ 'left': '-=100' });
break;
case 39: // right arrow key
$('#bottom_arrow').animate({ 'left': '+=100' });
break;
}
});

chicong cai
- 53
- 5