I'm trying to create a table to display an individual's BMI.
As part of this, I'd like, on :hover, for the <tr>
and <col>
(or <colgroup>
) to be highlighted also, in order for the intersection to be more apparent.
As the table will feature both metric and imperial measurements, the :hover doesn't have to stop at the cell (from any direction) and would, in fact, be a bonus if it extended from one axis to the other. I'm also using the XHTML 1.1 Strict doctype, if this makes a difference?
So...an example (the real table's...larger), but this should be representative:
<script>
tr:hover {background-color: #ffa; }
colgroup:hover,
col:hover {background-color: #ffa; }
</script>
...
<table>
<col class="weight"></col><colgroup span="3"><col class="bmi"></col></colgroup>
<tr>
<th></th>
<th>50kg</th>
<th>55kg</th>
<th>60kg</th>
</tr>
<tr>
<td>160cm</td>
<td>20</td>
<td>21</td>
<td>23</td>
</tr>
<tr>
<td>165cm</td>
<td>18</td>
<td>20</td>
<td>22</td>
</tr>
<tr>
<td>170cm</td>
<td>17</td>
<td>19</td>
<td>21</td>
</tr>
</table>
Am I asking the impossible, do I need to go JQuery-wards?
I came accross this neat way of doing it its from css-tricks.com I also prepared a fiddle whilst messing around with it nothing fancy but u can get the idea its with the same code provided by that css-trick page
//The Html
//The Js
Check out the fiddle here
Live answer (https://jsfiddle.net/craig1123/d7105gLf/)
There are already CSS and JQuery answers; however, I have written a simple pure javascript answer.
I first find all the
col
andtd
tags, get the column index of each cell by doingelement.cellIndex
, and then add a CSS class with a background onmouseenter
and removing it onmouseleave
.HTML
CSS
JS
Here is a fiddle
Here's a pure CSS method using no Javascript.
I used
::before
and::after
pseudo-elements to do the row and column highlighting.z-index
keeps the highlighting below the<tds>
in case you need to handle click events.position: absolute
allows them to leave the confines of the<td>
.overflow: hidden
on the<table>
hides the highlight overflow.It wasn't necessary, but I also made it select just the row or column when you're in the headers. The
.row
and.col
classes take care of this. If you wish the simplify, you can remove them.This works in all modern browsers (and degrades gracefully on older browsers by doing nothing).
Demo: http://jsfiddle.net/ThinkingStiff/rUhCa/
Output:
CSS:
HTML:
AFAIK CSS Hovers on
TR
's aren't supported in IE anyway, so at best the TR part of that will only work in Firefox.Never even seen a
:hover
work on a col/colgroup so not sure if that's possible...Think you might be stuck with a Javascript implementation.
Theres an example here that works (rows & cols) in Firefox but again its broken in IE... cols don't work.
There is a very decent jQuery plugin I've come across located here which does a very good job of this kind of thing with loads of examples. Preferentially I'd use that.