Asher G.
Asher G.

Reputation: 5001

Make table rows highlightable

I am trying to make the rows of a table have a highlight color when the mouse is hovering over them and I want the entire row to be selectable. I have tried:

<tr onmouseover="ChangeColor(this, true);" 
              onmouseout="ChangeColor(this, false);" 
              onclick="DoNav('http://www.yahoo.com/');">

but the problem is that I have an external css style sheet that colors these individual rows and the javascript code to change the color has no effect if their are colors specified in my css style sheet. so for example I want the rows to be green normally and highlight white when hovered over and clicked. If i have the color specified as green, then it is always green, even when I mouse over them. If i don't have the color specified as green then the javascript works. This is rather annoying. And I also have the color of the rows alternating.

Can anyone help me with an easy solution?

here the javascript function I was using for onmousehover and onmouseclick:

function ChangeColor(tableRow, highLight)
{
    if (highLight)
    {
      tableRow.style.backgroundColor = '#89ae37';
    }
    else if (this.class == alt)
    {
        tableRow.style.backgroundColor = '#EAF2D3';
    }   
    else
    {
        tableRow.style.backgroundColor = '#A7C942';
    }
}

function DoNav(theUrl)
{
  document.location.href = theUrl;
}

Upvotes: 0

Views: 10430

Answers (3)

OnResolve
OnResolve

Reputation: 4032

You can do this will jquery very easily by adding and removing a css class which can do much more than just the background color. Here is an example I made for you that changes the background on mouse over.

http://jsfiddle.net/zHr4n/8/

Upvotes: 1

nnnnnn
nnnnnn

Reputation: 150010

You can do the hover effect with no JS at all if you put something like the following into your stylesheet:

tr:nth-child(odd) { background-color : #EAF2D3; }
tr:nth-child(even) { background-color : #A7C942; }
tr:hover { background-color : #89ae37; }
​

Demo: http://jsfiddle.net/nnnnnn/zHgsf/

Note that you don't even need to specify the class="alt" on alternate rows because the :nth-child(odd) and :nth-child(even) selectors take care of it for you.

Upvotes: 4

Greg
Greg

Reputation: 21899

This kind of behaviour seems to be styling the application, rather than providing any logic, which screams out to me to be placed into style sheets, rather than JavaScript.

To achieve a whole row of a table highlighting that matches your example, in CSS:

table tr {
    background: #a7c942;
}
table tr:hover {
    background: #89ae37;
}
table tr.alt:hover {
    background: #eaf2d3;
}

Upvotes: 3

Related Questions