Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add jQuery hover effect across two tables

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>
like image 258
James Avatar asked Apr 19 '26 20:04

James


1 Answers

The trick is to grab all the <tr>s at the beginning and then combine $(this).index(), filter, and :nth-child to select the right rows in both tables at once:

var $trs = $('table.grid tr:not(:first-child)');
$trs.hover(
    function() {
        var i = $(this).index() + 1;
        $trs.filter(':nth-child(' + i + ')').addClass('highlight');
    },
    function() {
        var i = $(this).index() + 1;
        $trs.filter(':nth-child(' + i + ')').removeClass('highlight');
    }
);

Demo: http://jsfiddle.net/ambiguous/54thG/

The index call gives you the position of the <tr> being hovered with respect to its siblings in $trs, then you adjust by 1 because index is zero-based but :nth-child (being a CSS selector) is one-based, and fiddle with the class on both rows at once.

like image 68
mu is too short Avatar answered Apr 22 '26 10:04

mu is too short



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!