views:

106

answers:

3
+3  A: 

You should be able to focus the various cells, I will put an example together using .focus()

Here is the example.

Please bear in mind that...

a) There is nothing in this example to stop you from going out of bounds, you would need to restrict the values of currentRow and currentCell to the number of cells and prevent them from going below 0.

b) At the moment, there is no code to remove the green text, which is what I've used to show the current focus. This means a green trail is left behind.

You could solve both of the above fairly easily, but they would make the example more complicated...

    var currentRow = 0;
    var currentCell = 0;

    function ChangeCurrentCell() {
        var tableRow = document.getElementsByTagName("tr")[currentRow];
        var tableCell = tableRow.childNodes[currentCell];
        tableCell.focus();
        tableCell.style.color = "Green";
    }
    ChangeCurrentCell();

    $(document).keydown(function(e){
        if (e.keyCode == 37) { 
           currentCell--;
           ChangeCurrentCell();
           return false;
        }
        if (e.keyCode == 38) { 
           currentRow--;
           ChangeCurrentCell();
           return false;
        }
        if (e.keyCode == 39) { 
           currentCell++;
           ChangeCurrentCell();
           return false;
        }
        if (e.keyCode == 40) { 
           currentRow++;
           ChangeCurrentCell();
           return false;
        }
    });
Sohnee
I don't think that I explained myself very well. Anyway, thank you for some hints :-)
Faili
I mark this as solved because it's understandable and may help others.
Faili
+2  A: 

here is my version...

demo

var active;
$(document).keydown(function(e){
    active = $('td.active').removeClass('active');
    var x = active.index();
    var y = active.closest('tr').index();
    if (e.keyCode == 37) { 
       x--;
    }
    if (e.keyCode == 38) {
        y--;
    }
    if (e.keyCode == 39) { 
        x++
    }
    if (e.keyCode == 40) {
        y++
    }
    active = $('tr').eq(y).find('td').eq(x).addClass('active');
});​
Reigel
2 things; you need to `return false;` from the event to prevent the page from scrolling if it has scrollbars and second, you need to scroll the active td into view if it's not currently visible on the screen. [example](http://jsfiddle.net/ZkaSu/1/)
Andy E
+2  A: 

Here is a version that allows for the following

  1. constrains at start and end of the table (first and last cell of the table)
  2. wraps at the end of each row and moves to the next
  3. scrolls the current cell into view if there is scrolling required to see it
  4. supports mouse-click to select a cell

Code at : http://jsfiddle.net/BdVB9/

Gaby