Skip to content

Instantly share code, notes, and snippets.

@mervick
Forked from krcourville/gist:7309218
Created November 16, 2020 23:27
Show Gist options
  • Save mervick/02de55c224dbe7c02cdaeae37269e0dd to your computer and use it in GitHub Desktop.
Save mervick/02de55c224dbe7c02cdaeae37269e0dd to your computer and use it in GitHub Desktop.
Navigate table with arrow keys using jQuery
$('table.arrow-nav').keydown(function(e){
var $table = $(this);
var $active = $('input:focus,select:focus',$table);
var $next = null;
var focusableQuery = 'input:visible,select:visible,textarea:visible';
var position = parseInt( $active.closest('td').index()) + 1;
console.log('position :',position);
switch(e.keyCode){
case 37: // <Left>
$next = $active.parent('td').prev().find(focusableQuery);
break;
case 38: // <Up>
$next = $active
.closest('tr')
.prev()
.find('td:nth-child(' + position + ')')
.find(focusableQuery)
;
break;
case 39: // <Right>
$next = $active.closest('td').next().find(focusableQuery);
break;
case 40: // <Down>
$next = $active
.closest('tr')
.next()
.find('td:nth-child(' + position + ')')
.find(focusableQuery)
;
break;
}
if($next && $next.length)
{
$next.focus();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment