Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind Keyboard to left/right navigation

I am a photographer and have a website where I am unable to edit the 'template' structure but can upload javascript/css etc.

I want to bind next/prev navigation to keyboard right/left.

The structure of the links are:

<div class="image_navigation">
      <h4>Image Navigation</h4>
      <ul>
        <li class="index"><a href="LINKURL">Index</a></li>
        <li class="previous"><a href="LINKURL">Previous</a></li>
        <li class="next"><a href="LINKURL">Next</a></li>
      </ul>
    </div>

I referred to this and managed to create this.

$(function() {$(document).keyup(function(e) {
switch(e.keyCode) { case 37 : window.location = $('li.prev').attr('href'); break;
    case 39 : window.location = $('li.next').attr('href'); break; }});});

This is where I am stuck. It does not work because it assumes the I am refereing to a href tag but am refering to the li that contains it.

Any ideas would be much appreciated!

like image 917
tjh Avatar asked Jan 18 '12 11:01

tjh


2 Answers

window.location = $('li.next a').attr('href');
like image 144
Alex Pliutau Avatar answered Sep 29 '22 03:09

Alex Pliutau


I found this question when looking for dupes on this question and decided to share the little bit of jQuery I wrote to answer that one modified for your selectors:

// when the document is ready, run this function
jQuery(function( $ ) {
    var keymap = {};

    // LEFT
    keymap[ 37 ] = "li.prev a";
    // RIGHT
    keymap[ 39 ] = "li.next a";

    $( document ).on( "keyup", function(event) {
        var href,
            selector = keymap[ event.which ];
        // if the key pressed was in our map, check for the href
        if ( selector ) {
            href = $( selector ).attr( "href" );
            if ( href ) {
                // navigate where the link points
                window.location = href;
            }
        }
    });
});
like image 25
gnarf Avatar answered Sep 29 '22 04:09

gnarf