html - Background color is not changing on mouseover, mouseout event


Keywords:html 


Question: 

I have a simple html table layout as:

<table class="grid">
<thead>
<tr><th>1st Col</th><th>2nd Col</th><th>3rd Col</th><th>4th Col</th></tr>
</thead>
<tbody>
<tr><td>AAAA</td><td>BBBB</td><td>CCCC</td><td>DDDD</td></tr>
<tr><td>aaaa</td><td>bbbb</td><td>cccc</td><td>dddd</td></tr>
<tr><td>AAaa</td><td>BBbb</td><td>CCcc</td><td>DDdd</td></tr>
<tr><td>aaAA</td><td>bbBB</td><td>ccCC</td><td>ddDD</td></tr>
</tbody>
</table>

The background color of this table is defined in css:

table.grid > * > tr > * {
  border-right: 4px groove #D1D1D1;
  border-bottom: 4px groove #D1D1D1;
  padding: 0;
  background-color: #FFFFCC;
}

So, on load, the rows of this table are light yellow (#FFFFCC). While a user moves their cursor over the table, I want the color of the respective rows to change to give a highlight effect. I have used following jquery code to accomplish the highlighting effect:

$("body").on("mouseover mouseout",".grid > tbody > tr", function(){
            $(this).toggleClass("highlight");
});

and the highlight class is in again in the same css file:

tr.highlight{
  color: red;
  font-style: italic;
  background-color: green;
}

I found that, except for the background-color of the respective row, the font style and font color is changing. So the code is working to some extent but not completely.

But if I remove the background-color style from css, i.e, on load the table is white, the background-color of rows is changing to green while moving cursor over it:

table.grid > * > tr > * {
  border-right: 4px groove #D1D1D1;
  border-bottom: 4px groove #D1D1D1;
  padding: 0;
  //background-color: #FFFFCC;<--- I have to remove this line
}

Do you have any idea, how can I change the rows color if it is already given a background-color on load?


1 Answer: 

Those CSS selectors are really bad, and you don't need JS for the hover effect. Simplify it.

tr.highlight won't affect anything since you're setting the background color to the children of tr, not the tr itself.

Also, read about CSS specificity.


Here's a working code:

table.grid tr td {
  border-right: 4px groove #D1D1D1;
  border-bottom: 4px groove #D1D1D1;
  padding: 0;
  background-color: #FFFFCC;
}

table.grid tr:hover td{
  color: red;
  font-style: italic;
  background-color: green;
}
<table class="grid">
<thead>
<tr><th>1st Col</th><th>2nd Col</th><th>3rd Col</th><th>4th Col</th></tr>
</thead>
<tbody>
<tr><td>AAAA</td><td>BBBB</td><td>CCCC</td><td>DDDD</td></tr>
<tr><td>aaaa</td><td>bbbb</td><td>cccc</td><td>dddd</td></tr>
<tr><td>AAaa</td><td>BBbb</td><td>CCcc</td><td>DDdd</td></tr>
<tr><td>aaAA</td><td>bbBB</td><td>ccCC</td><td>ddDD</td></tr>
</tbody>
</table>