Search code examples
htmlcsshoverrow

How to apply hover on the same row on two different tables?


I have two different tables in my html, and lets assume they all have the same data collection - meaning the rows are representing the same object in the collection. I would like to apply a following functionality: when I hover on the row N in Table 1, it highlights row N in Table 1 and the same row in Table 2. I was able to get it done, however I had to manipulate my collection - I added .hover property on object, and treated it as a flag on mouse enter and mouse leave, and added specific styles according. However, I know this should not be done this way - as it breaks the two way data binding rule.

Any ideas on how I can achieve that without manipulating my data?


Solution

  • You could achieve this by using little jQuery:

    var tr_class;
    $('.table1 tr').hover(
      function(){
        tr_class = $('this').attr('class');
        $('this').addClass('highlightBg');
        $('.table2 ' + tr_class).addClass('highlightBg');
    }, 
      function(){
       $(this).removeClass('highlightBg');
       $('table2 ' + tr_class).removeClass('highlightBg');
    });
    $('.table2 tr').hover(
      function(){
        tr_class = $('this').attr('class');
        $('this').addClass('highlightBg');
        $('.table1 ' + tr_class).addClass('highlightBg');
    }, 
      function(){
       $(this).removeClass('highlightBg');
       $('table1 ' + tr_class).removeClass('highlightBg');
    });
    

    Both of your table rows need to have a class like a row number for example counting them:

    <tr class='1'>...</tr>
    <tr class='2'>...</tr>
    

    .highlightBg defines a background-color for highlighted state, in this example .table1 and .table2 are the classes of the tables.

    Think that should do the work.