Kez
Kez

Reputation: 209

jump to previous or next element on up or down key press with jQuery

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

Upvotes: 2

Views: 1363

Answers (1)

Vahan
Vahan

Reputation: 169

  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;
}

Upvotes: 2

Related Questions