Search code examples
javascriptjqueryonclickonkeypress

Navigate with keyboard in lightbox / recognize 'onkeypress' as 'onclick'


I try to navigate with keyboard arrows Left/Right through my lightbox, but my script doesn't work.
It will be great if the script recognizes 'onkeypress' as 'onclick', because I have to use 'onclick' for Google Analytics Stats.
Any idea ? Thanks.

Script :

jQuery(function( $ ) {
var keymap = {};


keymap[ 37 ] = ".prev";

keymap[ 39 ] = ".next";

$( document ).on( "keyup", function(event) {
    var href,
        selector = keymap[ event.which ];
    if ( selector ) {
        href = $( selector ).attr( "href" );
        if ( href ) {
            window.location = href;
          }
        }
    });
});

HTML :

<li>
  <a href="#example-01" onclick="_gaq.push(['_trackPageview', location.pathname + location.search + '#example-01']);"><img src="images/thumbs/example-01.jpg" /></a>
    <div class="lb-overlay" id="example-01">
        <img src="images/full/example-01.jpg" />
                <div>
                    <a href="#example-00" onclick="_gaq.push(['_trackPageview', location.pathname + location.search + '#example-00']);" class="prev">PREV</a>
                    <a href="#example-02" onclick="_gaq.push(['_trackPageview', location.pathname + location.search + '#example-02']);" class="next">NEXT</a>
                </div>
     </div>
 </li>

Solution

  • This code works for my problem :

    var current = 0;
        $(document).on('keyup', function (e) {
            switch (e.which) {
                case 37:
                    $('.lb-prev')[--current].click();
                    break;
    
                case 39:
                    $('.lb-next')[++current].click();
                    break;
        }
    });