views:

135

answers:

2

In Jquery, how can I set an event such that when user is browsing some pictures, and presses the left/right arrow key, it calls a function which can be used to show the previous/next photos? I only need to know how to check if the key pressed was the right/left arrrow key and ignore all other key preses.

The image will be in its own div.\

+1  A: 

Use the jQuery keypress event like so:

$("input").keypress(function (e) {
  if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25)
                    || (97 <= e.which && e.which <= 97 + 25)) {
    var c = String.fromCharCode(e.which);
    $("p").append($("<span/>"))
          .children(":last")
          .append(document.createTextNode(c));
  } else if (e.which == 8) {
    // backspace in IE only be on keydown
    $("p").children(":last").remove();
  }
  $("div").text(e.which);
});

I'm not sure which value will be present for left/right but a little experimenting with this script should get you going

Spencer Ruport
+3  A: 

I've used this in the past. It works for me in the enviornments I've used (linux and windows with FF)

$(document).keypress( function(e) { 
  if (e.keyCode === 37) {
     // left
  }
  else if (e.keyCode === 39) {
     // right
  }
});

That being said, I'm not so sure connecting on the arrow keys is a good idea since a user could change text size and cause the scroll bar to appear. Arrowing would change the picture unexpectedly.

seth