I took thesocialgeek's answer as confirmation that there's no CSS-only implementation and that this is the best approach in JS.
But I've implemented it in the more generic way so the code could go into the central JS script for my whole site. It should solve the problem for any table cell with rowspan
defined.
This is my CSS:
tr.hover,
th.hover,
td.hover,
tr.hoverable:hover {
background-color: grey;
}
An ordinary table row will be hovered by CSS' :hover
pseudo-class. Any row as well as <th>
s and <td>
s will be hovered by force when the .hover
class is added. That alone work's perfect for simple tables.
This is the JS code as a generic solution to complex tables:
$(document).ready(function() {
$('tr.hoverable [rowspan]').each(function(index, cell) {
var $cell = $(cell);
var rowspan = $cell.attr('rowspan');
var limit = rowspan - 1;
var $this_row = $cell.closest('tr');
var $next_rows = $this_row.nextAll('tr:lt(' + limit + ')');
$next_rows.hover(
function() {$cell. addClass('hover')},
function() {$cell.removeClass('hover')}
);
});
});
It adds event listeners for mouseenter
and mouseleave
to the rows following a row with the rowspan
attribute set. The whole trick is to collect the right elements and then simply the CSS class needs to be toggled.
Problem still to be solved: On my page the event listeners are called three times each. I don't know exactly why. It's a bit useless but the code is not as fat as I could not ignore that.
I tested the code only in Firefox 22 with jQuery 2.0.3 where the result is perfectly like intended.
Update: I found it useful and extended the code to highlight all rows related to the rowspan
cell when this cell is hovered. Add the following snippet to the long function above:
$cell.hover(
function() {$next_rows. addClass('hover')},
function() {$next_rows.removeClass('hover')}
);