0

I want to trigger a click event on another element, when a left or right arrow is pressed. Here is the code:

$(window).keypress(function (e) {
  var key = e.which;
  if(key == 13 || key == 39) { // the enter key code or right arrow
    $('.next').click();
    return false;  
  } else if(key == 37) { // left arrow
    $('.prev').click();
    return false;  
  }
});

With Enter key it works like a charm, however on arrow press, nothing happens, like a Magikarp that uses splash! :) What am I missing?

Relevant question: Press left and right arrow to change image?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
gsamaras
  • 71,951
  • 46
  • 188
  • 305

1 Answers1

2

The arrow keys don't trigger a keypress event, but they do trigger a keyup or keydown event.

Best to use keyup, because keydown can be triggered multiple times while you're holding down a key.

$(window).keyup(function (e) {
  var key = e.which;
  if(key == 13 || key == 39) { // the enter key code or right arrow
    $('.next').click();
    return false;  
  } else if(key == 37) { // left arrow
    $('.prev').click();
    return false;  
  }
});
Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79
  • Once again Rick, thank you! Your edit was the answer to the question I was about to ask! – gsamaras Nov 17 '15 at 23:05
  • keyCode is [deprecated](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent). It's better to use `key` or `code` above IE9+ . – allenhwkim Nov 15 '17 at 16:55