rashmi
rashmi

Reputation: 619

arrow key navigation in table using jquery

i have application in which i navigate among table cell using arrow key. i have an issue here

1) if focus is in first cell of first row pressing left key will make focus invisible 2) if focus is in last cell of last row pressing right key makes focus invisible.

how do i make focus stay in same cell if the cell is first cell of first row(when left key is pressed) and same with last cell of last row (right key is pressed)

here is code:

switch(e.keyCode)
    {
      case 37:
        // Left
        button = cell.prev('td').find('button');
        if (button.length == 0)
        {
          // Nothing further left, go to end of
          // previous row
          button = cell.parent('tr').prev('tr').find('td:last button');

        }
        break;
      case 38:
        // Up
        row = cell.parent('tr');
        index = row.children('td').index(cell);
        button = row.prev('tr').find('td:eq(' + index + ') button').length === 0 ? row.find('td:eq(' + index + ') button') : row.prev('tr').find('td:eq(' + index + ') button');
        break;
      case 39:
        // Right
        button = cell.next('td').find('button');
        if (button.length == 0)
        {
          // Nothing further right, go to beginning of
          // next row
          button = cell.parent('tr').next('tr').find('td:first button');
        }
        break;
      case 40:
        // Down
        row = cell.parent('tr');
        index = row.children('td').index(cell);
        button = row.next('tr').find('td:eq(' + index + ') button').length === 0 ? row.find('td:eq(' + index + ') button') : row.next('tr').find('td:eq(' + index + ') button');;
        break;
    }

Upvotes: 2

Views: 3106

Answers (1)

mVChr
mVChr

Reputation: 50177

It's hard to tell without a bit more of your code, but to stay on your current cell if no next/prev button is found you should just have to add the following code after your switch statement:

if (button.length == 0) button = cell.find('button');

Upvotes: 1

Related Questions