2

I'm making a gallery and trying to figure out how to program the arrow keys to navigate the gallery.

So, pressing the left arrow would go to the previous image url:

function window.location = 'http://www.example.com/prevphoto.php';

Pressing the right arrow would go to the next image url.

function window.location = 'http://www.example.com/nextphoto.php';

Update (Thanks Haxxed pointing me in the right direction) This is where I'm at, but it's not working. Can you see why?

$('body').keypress(function (e) {
    if (e.which == 37) {
        // Left Arrow Pushed
        window.location = "/prevphoto.php";
    } else if (e.which == 39) {
        // Right Arrow Pushed
        window.location = "/nextphoto.php";
    }
}); 
Jon Adams
  • 24,464
  • 18
  • 82
  • 120
Alaska Zach
  • 100
  • 3
  • 11

3 Answers3

2

Basically you'll need to make the body tag have a keypress event (or use jquery to make an event listener) and then just check the keycodes (Left Arrow is 37, Right is 39) and then use window.location to redirect the page. All Key Codes

<head>
    <script>
           function e(event){
            if(event.keyCode == 37){
                //Left Arrow Pushed
                window.location = "../prevphoto.php";
            }else if(event.keyCode == 39){  
                //Right Arrow Pushed     
                window.location = "../nextphoto.php";
            }        
        } 
    </script>
</head>    
<body onKeyPress="e(event)" >

</body>​
Charles
  • 1,121
  • 19
  • 30
1

Try putting the script in your head tags, then modifying the body to use document.

$(document).keypress(function (e) {

    if (e.which == 37) {
        //Left Arrow Pushed
        window.location = "/prevphoto.php";
    } else if (e.which == 39){ 
        //Right Arrow Pushed     
        window.location = "/nextphoto.php";
    }

}); 
Felix Guo
  • 2,700
  • 14
  • 20
  • yeah that seems logical but it's not working either. Here's the site [link](http://www.zacharysheldon.com/print/17/Sunset-Light-at-Night) – Alaska Zach Dec 07 '12 at 04:16
1

See this related answer: https://stackoverflow.com/a/5597114/380487

You'll need to listen for the keydown event, not the keypress event.

Community
  • 1
  • 1
nrabinowitz
  • 55,314
  • 10
  • 149
  • 165