2

I'm trying to jump up and down on arrow press. I just need to trigger a click on the next or previous item each time the up or down arrow is pressed, but jQuery no likey. . .

 $('body').on("keyup", function(e) {

                var code = e.which;
                if (code == 40) {

                 e.preventDefault();    
                // down here
               $('.cv_item').next().trigger( "click" );

                } else if (code == 38) {

                 e.preventDefault();    
                // up here
           $('.cv_item').previous().trigger( "click" );
                }
            });

UPDATED:FIDDLE

Kez
  • 209
  • 2
  • 18

1 Answers1

2
  1. So previous() should be prev().
  2. You need to store your current active element to jump to the next or previous one
  3. And here is how to trigger a click on a link: jQuery.trigger('click') not working

And JSFIDDLE:

$currentLi = $('.cv_item').last().closest('li');

$('body').on("keyup", function(e) {              
    var code = e.which;

    if (code == 40) {
        e.preventDefault();    
      // down here
      $currentLi = $currentLi.next();
      if ( $currentLi.length==0 )
        $currentLi = $('.cv_item').first().closest('li'); 

      $('.cv_item').removeClass('active-link');

      $link = $currentLi.find('.cv_item');
      $link.addClass('active-link');      
      $link[0].click();

        } else if (code == 38) {
        e.preventDefault();    
      // up here
      $currentLi = $currentLi.prev();
      if ( $currentLi.length==0 )
        $currentLi = $('.cv_item').last().closest('li');

      $('.cv_item').removeClass('active-link');

      $link = $currentLi.find('.cv_item');
      $link.addClass('active-link');      
      $link[0].click();

    }
});

Update: The scrip has changed to add a CSS class to the <a> element and the class definition is simple:

a.active-link {
    color: #0f0;
}
Community
  • 1
  • 1
Vahan
  • 169
  • 3
  • 12
  • Is is great, but doesn't show which is active, i tried adding a class to currentLi, but didn't work. – Kez Aug 23 '16 at 11:02