views:

4094

answers:

4

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
Is there any purpose for the return?
Shadow
It stops any further keydown events being hit.
s_hewitt
Oh right...I just wrote it with a switch and breaks.
Shadow
Shadow: no, he means it stops the keydown event from firing on other DOM elements
JasonWoof
Except 39 is also apostrophe, isn’t it?
Paul D. Waite
+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
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
+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
I was reading where it said it was based on another library, and assumed that list of supported keys still applied.
Shadow
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