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?

2
  • So add a keypress handler and look at the keycode. Commented May 12, 2014 at 16:13
  • You might want a keyup event (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. Commented May 12, 2014 at 16:14

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.