Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery DataTable Keydown

I am having trouble capturing keydown events using JQuery DataTable. My goal is to allow users to navigate the rows of the table using the arrow keys. Therefore, I would like to catch keydown events and move the table's selected row (this is something I am keeping track of outside the datatable using a class for the selected row) when a user presses the arrow key. However, I cannot seem to catch the keydown events.

For example, the code below does not work:

$('#myTable tbody').keydown(function (event){...});

My thought is that the issue is the table does not have focus, but perhaps this is the wrong path. For example, even if I add the following, I do not catch keydown events with the above code:

 $('#myTable tbody').click(function(e){ $('#myTable tbody').focus();});

I can catch the keydown with the $(document) but this is not desirable.

Thanks.

like image 600
JDG Avatar asked Jan 30 '13 19:01

JDG


1 Answers

Here's a working solution...code could be cleaned up a bit (and there are bugs, e.g. no limit checking), but the effect is there:

http://jsfiddle.net/BLSully/Xdkea/

The 'key' is giving the table a tabindex so it becomes "focusable". It does not need to be zero, but it needs to be "something" so that the keypress events work on it

<table id="myTable" tabindex=0>
    <tbody>
        <tr><td>Row 1</td></tr>
        <tr><td>Row 2</td></tr>
        <tr><td>Row 3</td></tr>
        <tr><td>Row 4</td></tr>
        <tr><td>Row 5</td></tr>
    </tbody>
</table>

JavaScript:

$(function(){
    var focusedRow = null;
    $('#myTable').on('keydown', function(ev){
        console.log(ev.keyCode);
        if(focusedRow == null) {
            focusedRow = $('tr:nth-child(1)', '#myTable');
        } else if(ev.keyCode === 38) {
            focusedRow.toggleClass('focused');
            focusedRow = focusedRow.prev('tr');
        } else if(ev.keyCode === 40) {
            focusedRow.toggleClass('focused');
            focusedRow = focusedRow.next('tr');
        }
        focusedRow.toggleClass('focused');
    });
    $('#myTable').focus();
});
like image 177
BLSully Avatar answered Oct 13 '22 19:10

BLSully