2

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"
Colin Brock
  • 21,267
  • 9
  • 46
  • 61
sd_dracula
  • 3,796
  • 28
  • 87
  • 158
  • I would think that it would be easier to just add and remove a class rather than store and retrieve the specific style. – j08691 Jun 15 '12 at 16:46

2 Answers2

4

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; }
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • Doesn't quite work as expected, for one all of the rows are being highlighted yellow when i mouse over not just one and how to set the TR bgcolor for the whole row onlick? – sd_dracula Jun 16 '12 at 10:56
  • I suppose it won't work since the table is nested withing a td of another table – sd_dracula Jun 16 '12 at 11:29
  • No it would work if you cahnge the CSS rules to only target the one table that you want highlighted. Make the rules more specific. For onclick add JavaScript that sets a class on the row. – epascarello Jun 16 '12 at 11:50
3

Even if I agree that is better to make it with css hover, I like to answer to the question, how to do it with javascript.

You can save it on one attribute and use it to restore it as:

<script>
function setBackground(me, color)
{
   me.setAttribute("data-oldback", me.style.background);       
   me.style.background=color;
}

function restoreBackground(me)
{
    me.style.background = me.getAttribute("data-oldback");
}    
</script>

and

  <tr onmouseover="setBackground(this, 'Red');" 
   onmouseout="restoreBackground(this);" 
     style="background:blue;" >

and a test : http://jsfiddle.net/AdDgS/3/ and this http://jsfiddle.net/AdDgS/4/

Aristos
  • 66,005
  • 16
  • 114
  • 150