Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight rows in HTML table (hovered over row and preceding rows)

Assuming an example table:

<table>
   <tr>
     <th>Head 1</th>
     <th>Head 2</th>
    </tr>
    <tr>
      <td>Data 1</td>
      <td>Data 2</td>
    </tr>
    <tr>
      <td>Data 3</td>
      <td>Data 4</td>
    </tr>
    <tr>
      <td>Data 5</td>
      <td>Data 6</td>
    </tr>
    <tr>
      <td>Data 7</td>
      <td>Data 8</td>
    </tr>
</table>

I'm looking for the best technique to highlight the rows <= n, where n is the hovered over row (excluding the header row). For example, if the mouse is over

<tr>
  <td>Data 5</td>
  <td>Data 6</td>
</tr>

the following part of the table should be highlighted:

<tr>
  <td>Data 1</td>
  <td>Data 2</td>
</tr>
<tr>
  <td>Data 3</td>
  <td>Data 4</td>
</tr>
<tr>
  <td>Data 5</td>
  <td>Data 6</td>
</tr>

Any ideas how this effect could be achieved?

like image 839
asliwinski Avatar asked Mar 25 '14 12:03

asliwinski


People also ask

How do you highlight rows in a table?

To select an entire table, click in the table, and then click the Table Move Handle in the upper-left corner. To select a row, column, cell, or group of cells, click and drag your mouse pointer to highlight the cells you want.

How do you highlight text in a table in HTML?

Highlight using the HTML5 <mark> tag If you are working on an HTML5 page, the <mark> tag can quickly highlight text. Below is an example of the how to use the mark tag and its result. If your browser supports the <mark> tag, "highlighted text" should have a yellow background.

How do you color a row in HTML?

The HTML <tr> bgcolor Attribute is used to specify the background color of a table row. It is not supported by HTML 5. Attribute Values: color_name: It sets the background color by using the color name.


2 Answers

Basically, you could see the thing the opposite way : any tr after hovered tr should have no background: test this :

table:hover tr {
  background:gray;
}
table:hover tr:hover ~tr {
  background:none;
}

DEMO


=============== EDITED from request in comments ================

React only on last element in row.

BEWARE :This option doesn't allow to click in cells but last one of each row.


table {
  pointer-events:none;
}
table tr :last-child {
  pointer-events:auto;
  cursor: pointer;
}
like image 78
G-Cyrillus Avatar answered Oct 21 '22 21:10

G-Cyrillus


Try this: (fiddle: http://jsfiddle.net/5SLN3/)

$('tr').hover(
    function(){
        $(this).addClass('hover').prevAll().addClass('hover');
    },
    function(){
        $(this).removeClass('hover').prevAll().removeClass('hover');
    }
)

and the style:

<style>
tr.hover td{background-color:#888}
</style>
like image 30
Thomas Laier Pedersen Avatar answered Oct 21 '22 20:10

Thomas Laier Pedersen