Search code examples
javascriptjqueryarrow-keys

Custom arrow key navigation not working properly (one part works)


I have a large HTML table with dynamically added rows.

The table has a standard structure (incl. thead, tbody and tfoot).

Within this table there are editable TDs (which have the class "editable" and contain a contenteditable div) and non-editable TDs (which dont't have the class "editable" and do not contain a div).

I am trying to create a custom arrow key navigation that allows me to jump from one editable TD to next or previous one (like in an Excel table).

To test this I used the below example but this only works partially, i.e. the alerts are shown correctly but I am not able to do anything with the corresponding div (e.g. change its background or add a text etc.).

Can someone tell me what I am doing wrong here ?

My jQuery (in doc ready):

$(document).keydown(function(e){
    switch(e.which){
        case 37: // left arrow
            alert('test left');
            $(this).closest('td').prevUntil('td.editable').find('div').text('test');
            break;
        case 39: // right arrow
            alert('test right');
            $(this).closest('td').nextUntil('td.editable').find('div').text('test');
            break;
        default: // exit for other keys
            return;
    }
    e.preventDefault(); // prevent default action
});

My HTML (example row):

<tr>
    // ...
    <td class="editable"><div contenteditable="true"></div></td> <!-- editable -->
    <td class="editable"><div contenteditable="true"></div></td> <!-- editable -->
    <td></td> <!-- non-editable -->
    <td></td> <!-- non-editable -->
    <td class="editable"><div contenteditable="true"></div></td> <!-- editable -->
    // ...
</tr>

Solution

  • this in your code refers do document not single element

    if you use $(e.target) you can get single element

    Also you should use next() function instead of nextUntil()

    $(e.target).closest('td').nextAll('td.editable:first').find('div').text('test');