How do I go about binding a function to left and right arrow keys in Javascript and/or jQuery? I looked at the js-hotkey plugin for jQuery (wraps the built-in bind function to add an argument to recognize specific keys), but it doesn't seem to support arrow keys.
+12
A:
$(document).keydown(function(e){
if (e.keyCode == 37) {
alert( "left pressed" );
return false;
}
});
Character codes:
37 - left
38 - up
39 - right
40 - down
Josh
2009-09-09 23:48:38
Is there any purpose for the return?
Shadow
2009-09-09 23:53:05
It stops any further keydown events being hit.
s_hewitt
2009-09-09 23:56:57
Oh right...I just wrote it with a switch and breaks.
Shadow
2009-09-10 00:13:18
Shadow: no, he means it stops the keydown event from firing on other DOM elements
JasonWoof
2009-09-10 01:17:59
Except 39 is also apostrophe, isn’t it?
Paul D. Waite
2010-04-30 15:57:23
+9
A:
You can use the keyCode of the arrow keys (37, 38, 39 and 40 for left, up, right and down):
$('.selector').keydown(function (e) {
var keyCode = e.keyCode || e.which,
arrow = {left: 37, up: 38, right: 39, down: 40 };
switch (keyCode) {
case arrow.left:
//..
break;
case arrow.up:
//..
break;
case arrow.right:
//..
break;
case arrow.down:
//..
break;
}
});
Check the above example here.
CMS
2009-09-09 23:49:21
I'm not sure about your use of the || operator in line 2. Isn't a value other than zero or nonzero implementation specific and not guaranteed? I would use something more like:var keyCode = (e.keyCode?e.keyCode:e.which);+1 for the use of the arrow object to give the cases readable names.
Mnebuerquo
2010-04-03 22:58:13
+1
A:
Are you sure jQuery.HotKeys doesn't support the arrow keys? On the live demo page (http://jshotkeys.googlepages.com/test-static-01.html) it has left, right, up, and down listed under the "special keys" section, and it works when I test it in IE7, Firefox 3.5.2, and Google Chrome 2.0.172...
Pandincus
2009-09-09 23:51:21
I was reading where it said it was based on another library, and assumed that list of supported keys still applied.
Shadow
2009-09-10 00:15:29
A:
This is a bit late, but HotKeys has a very major bug which causes events to get executed multiple times if you attach more than one hotkey to an element. Just use plain jQuery.
$(element).keydown(function(ev) {
if(ev.which == $.ui.keyCode.DOWN) {
// your code
return false; // don't execute the default action (scrolling or whatever)
}
});
mackstann
2010-07-25 06:28:35