euDennis
euDennis

Reputation: 327

Change color of a CSS when mouse hover an TD

I'm developing an site with a large table (18 row x 11 columns). To make it easier for who is looking that table, I made it hover an different color for the TR with that:

.responsive tr:hover {
    background-color: red;
}

But I want to make the same with the column. But if I use .responsive td:hover {background-color: blue;}, it just hovers the single TD, not the entire column. At least, every TD has the class col1, col2, etc.

How is it possible to change a CSS property when hovering the TD. If this is possible, I can change the background-color from class col1 when I hover the col1 TD.

Any idea?

Upvotes: 3

Views: 3250

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382132

There is no concept of column in HTML or CSS.

You must use javascript to do that.

Here's a solution using jQuery :

var clean = function(){
   $('td').removeClass('colHover');
}
$('td').hover(
    function() {
       clean();
       $('td:nth-child('+($(this).index()+1)+')').addClass('colHover');
    }, clean
);

Demonstration


Now, mainly for fun, if you want to handle colspan, you could do that :

var clean = function(){
   $('td').removeClass('colHover');
}
$('td').hover(
    function() {
       clean();
       var col = 0;
      $(this).prevAll().each(function(){col += parseInt($(this).attr('colspan')||'1')});
      $('tr').each(function(){
        var c = 0, done = false;
        $('td',this).each(function(){
          if (c>col && !done) {
            $(this).prev().addClass('colHover');
            done = true;
          }
          c += parseInt($(this).attr('colspan')||'1');
        });
        if (!done) $(this).find('td:last-child').addClass('colHover');
      });
    }, clean
);

Demonstration

Upvotes: 4

Related Questions