Search code examples
c#asp.netonclickrowonmouseover

javascript for highlight row and toggle onclick color


I need to be able do the following on a TR:

  • onmouseover highlight the whole row one colour
  • onclick the row highlight the row another colour (if you click the same row again it unhighlights the row - sets it to the original bgcolor)
  • a problem I have is that in my listview the row's bgcolor alternates between two colours.
  • the code below only works for highlighting one row at a time, the row needs to remain highlighted until it is clicked again.

Here is some code that I use for clicking to select which works but I need to change it so that it toggles the row highlight on/off

<script type="text/javascript"> 
var preEl;
var orgBColor;
var orgTColor;
function highlighttr(el, backColor, textColor) {
    if (typeof (preEl) != 'undefined') {
        preEl.bgColor = orgBColor;
        try { ChangeTextColor(preEl, orgTColor); } catch (e) { ; }
    }
    orgBColor = el.bgColor;
    orgTColor = el.style.color;
    el.bgColor = backColor;

    try { ChangeTextColor(el, textColor); } catch (e) { ; }
    preEl = el;
}


function ChangeTextColor(a_obj, a_color) {
    ;
    for (i = 0; i < a_obj.cells.length; i++)
        a_obj.cells(i).style.color = a_color;
}
</script>

Solution

  • This a traditional way which by the way is cross-browser (and platform).

    CSS

    .tr {background-color:#fff}
    .trOver {background-color:#ddd}
    .trClicked {background-color:#bbb}
    

    JS

    function over(o)
    {
        if ('trClicked' != o.className) o.className = 'trOver';
    }
    function out(o)
    {
        if ('trClicked' != o.className) o.className = 'tr';
    }
    function clicked(o)
    {
        o.className = ('trClicked' == o.className) ? 'tr' : 'trClicked';
    }
    

    HTML

    <tr class="tr" onmouseover="over(this)" onmouseout="out(this)" onclick="clicked(this)">
        // tds without defined background color...
    </tr>