Javascript – using mouseover/mouseout in gridview with alternating rows

asp.netgridviewjavascriptmouseover

I currently have a gridview with alternating colors, Silver and White, with a blue header (not selectable, obviously). Initially, I had this onmouseover/onmouseout thing working but for some reason, yesterday morning it failed to work, and all day yesterday, I have been struggling, googling for answers and coming up short. Here is the databound function:

protected void GridView_OnRowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onclick", "onGridViewRowSelected('" + j.ToString() + "')");
            e.Row.Attributes.Add("onmouseover", "HighlightOn(this)");
            e.Row.Attributes.Add("onmouseout", "HighlightOff(this)"); 
        }
    }

And here is the onmouseover and onmouse out functions:

function HighlightOn(rowid)
{   
    if (document.getElementById(gridViewCtlId).disabled == false)
    {
        if ($(selectedIndex).val() != rowid.rowIndex)
        {
            rowid.style.backgroundColor = '#8FBAEF';
        }
    }
}

function HighlightOff(rowid)
{
    if (document.getElementById(gridViewCtlId).disabled == false)
    {   
        if ($(selectedIndex).val() != rowid.rowIndex)
        {
            var modIdx = rowid.rowIndex % 2;
            if (modIdx == 0)
            {
                rowid.style.backgroundColor = 'Silver';
            }
            else
            {
                rowid.style.backgroundColor = 'White';
            }
        }
    }
}

selectedIndex is being set by this:

function getSelectedRow(rowIdx)
{
    getGridViewControl(rowIdx);
    if (gridViewCtl != null)
    {
        $(selectedIndex).val(rowIdx);
        return gridViewCtl.rows[rowIdx];
    }
    return null;
}

This function just gets the row by giving it the id of the row in a gridview (used for the onclick event to change the color of the row).

The problem is this: When I click on a row, it becomes highlighted. When I then move the mouse, the other rows become somewhat highlighted, which is correct, but when I click on another row, and move the mouse out of that row, it becomes de-highlighted. And when i click on it again, does it stay highlighted. selectedIndex is just a hidden field on the page. Does anyone see why this doesn't function properly? Thanks.

Best Answer

First of all you can solve this problem with some CSS (not supported in IE6):


tbody tr:hover td {
  background-color: orange;
}

If I were to use JavaScript I would use an unobtrusive technique. Then you can skip the C#. Here is how you can do it:


$(function () {
  $("tbody tr")
    .mouseenter(function () {
      $(this).addClass("Highlight");
    })
    .mouseleave(function () {
      $(this).removeClass("Highlight");
    });
});

You need some CSS for this to work:


tbody tr.Highlight td {
 background-color: orange;
}
Related Topic