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,438
  • 68
  • 55
  • 126
gsamaras
  • 69,751
  • 39
  • 173
  • 279

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
  • 34,132
  • 4
  • 45
  • 75
  • 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