jQuery - Table Row Highlighting

The following example shows how to use jQuery and simple CSS to create a table with highlightable and clickable rows (see working example here):

<style type="text/css">
.highlight{
color:white;
background-color:black;
cursor: pointer;
}
</style>

<table id="example" border='1'>
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
</tr>
</thead>
<tbody>
<tr onclick="alert('John Smith')">
<td>John</td>
<td>Smith</td>
</tr>
<tr onclick="alert('Jane Doe')">
<td>Jane</td>
<td>Doe</td>
</tr>
<tr onclick="alert('Bob Squarepants')">
<td>Bob</td>
<td>Squarepants</td>
</tr>
</tbody>
</table>

<script id="vups-script" type="text/javascript">
$(document).ready(function(){
$("#example tbody td").hover(function() {
$(this).parents('tr').addClass('highlight');
}, function() {
$(this).parents('tr').removeClass('highlight');
});
});
</script>

Comments

  1. any idea how to make rows highlight-able when using the plugin tablesorter by Christian Bach?

    ReplyDelete
  2. I haven't tried it, but inspecting the tablesorter HTML in Firebug it looks like the two methods should work together. That is, say you have a table with id #myTable, you would first attach the tablesorter and then run the code I supplied above to make the rows highlightable and clickable. It should look something like this:

    $(document).ready(function(){
    $("#myTable").tablesorter();
    $("#myTable tbody td").hover(function() { $(this).parents('tr').addClass('highlight');
    }, function() { $(this).parents('tr').removeClass('highlight');
    });
    });

    ReplyDelete
  3. Jay, see the following example for using this with tablesorter: http://dl.dropbox.com/u/642364/blogger/scripts/jq-highlight-ts.html

    The two changes I had to make was make the .highlight css rules !important, and tweak the code to add/remove the hover class as $(this).parents('tr').find('td') so that is adds the .highlight class directly on the cells rather than rows.

    There's probably easier pays to do this, like making the css rule '.highlight td' or using the jQuery .siblings method, etc.

    ReplyDelete
  4. Thank you very much.

    ReplyDelete

Post a Comment

Popular posts from this blog

Wkhtmltopdf font and sizing issues

Import Google Contacts to Nokia PC Suite

Can't delete last blank page from Word