0

I have two buttons:

$('#prev').click(function() {
   // some code
});

$('#next').click(function() { 
  // some other code
});

what I now want to do is adding a .keypress() handler to the site which triggers on arrow-left the #prev click and for arrow-right it triggers #next. Problem is how can I add this handler?

supersize
  • 13,764
  • 18
  • 74
  • 133
  • So add a keypress handler and look at the keycode. – epascarello May 12 '14 at 16:13
  • You might want a `keyup` event (http://api.jquery.com/keyup/). Make sure you attach to the document or something that will actually have focus. Otherwise your key events won't be fired as you expect. – drew_w May 12 '14 at 16:14

1 Answers1

3

You can check the keydown event and catch the left/right arrow key code.

If left/right arrow are pressed trigger the according button, arrow codes:

37 - left

38 - up

39 - right

40 - down

Code:

$('#prev').click(function () {
    alert('prev');
});

$('#next').click(function () {
    alert('next');
});

$(document).keydown(function (e) {
    if (e.keyCode == 37) {
        $('#prev').click();
        return false;
    }
    if (e.keyCode == 39) {
        $('#next').click();
    }
});

Demo: http://jsfiddle.net/IrvinDominin/6CYXH/

Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111