tr onmouse events

sd_dracula picture sd_dracula · Jun 15, 2012 · Viewed 8k times · Source

I want to be able to hover on a row and highlight all of it but I am having an issue with the code below since some cells have a different background.

 <tr style="" onmouseover="this.style.background='Red';" onmouseout="this.style.background='#595959'" >

That is fine all all cells have the same background but if I click a cell it highlights it and onmouseout="this.style.background='#595959'" will always reset it.

How can I change that to something like:

onmouseout="this.style.background='currentCellBGColor"

Answer

epascarello picture epascarello · Jun 15, 2012

It can be done with a pure CSS solution. No JavaScript needed

Pure CSS solution that will work in IE8+ all other modern day browsers

tr:hover td { background-color:yellow }
td.selected { background-color: green; }
tr:hover td.selected { background-color: lime; }

Fiddle

If you need IE7, you need to add a class onmosueover to the table row and remove the class onmouseout.

tr:hover td, tr.hover td { background-color:yellow }
td.selected { background-color: green; }
tr:hover td.selected, tr.hover td.selected { background-color: lime; }