I have two HTML tables in divs floated next to each other. The second div is scrollable in the horizontal direction, so in effect it looks like one big table where the first few columns are ‘frozen’ and the others can be scrolled.
The following jQuery works great to highlight a row in one table when the user hovers over it:
$("table.grid tr:not(:first-child)")
.hover(
function () { $(this).addClass("highlight"); },
function () { $(this).removeClass("highlight"); }
);
Note that the :not(:first-child) prevents the header being highlighted.
How can I amend this so that it also highlights the corresponding row in the other table (which also has a class of grid)?
In other words, if I hover over the nth row in either table, then the nth rows in both tables are highlighted.
EDIT: The HTML looks like:
<div>
<div style="float: left">
<table id="names" class="grid">
<tr><th>Last</th><th>First</th></tr>
<tr><td>Smith</td><td>John</td></tr>
<!-- etc -->
</table>
</div>
<div style="float: left; overflow-x: scroll">
<table id="results" class="grid">
<tr><th>Test 1</th><th>Test 2</th></tr>
<tr><td>50%</td><td>70%</td></tr>
<!-- etc -->
</table>
</div>
<div style="clear: both">
</div>
</div>
The trick is to grab all the
<tr>s at the beginning and then combine$(this).index(),filter, and:nth-childto select the right rows in both tables at once:Demo: http://jsfiddle.net/ambiguous/54thG/
The
indexcall gives you the position of the<tr>being hovered with respect to its siblings in$trs, then you adjust by 1 becauseindexis zero-based but:nth-child(being a CSS selector) is one-based, and fiddle with the class on both rows at once.