Search code examples
jqueryhtml-tablekeypress

Traversing over table rows adding a class


I have a table such as the follows:

<table border="1" width="400" cellpadding="3" cellspacing="3">
    <tr class="keydown"> <!-- Should this be a class? when down arrow is pressed class="selected" should be applied to this-->
        <td>Table Cell</td>
    </tr>
    <tr class="keydown">
        <td>Table Cell</td>
    </tr>
<table>

As the down arrow key is pressed (ascii 40?? or 31?) I want the first row in the table to be selected, i.e. a class should be applied to it highlight (i.e. change in bg colour) it. When the down arrow key is pressed again it should go to the next row. Is there a plugin for this? I'm messing around with jQuery but I'm a completely new at this.

jQuery:

<script type="text/javascript">

$().ready(function() {     
    $('#keydown').keypress(function() {
        $("#keydown").addClass("selected");
    }); 
});

</script>

Solution

  • It's recommended to use keyup for things like this, which key information is stored in the event argument. Also, your document ready isn't correct:

    $(function() { // or use: $(document).ready(function() {
        $('.keydown').keyup(function(e) {
            if (e.keyCode === '40')
                $(this).addClass('selected');
        }); 
    });