Chris Bier
Chris Bier

Reputation: 14445

Javascript hover effect removes pre defined style

I am using a tutorial from Imar Spaanjaars' web site to make an entire table row clickable and have a hover effect on it also. Once the user hovers over the table row it removes the pre defined background color for that row. I want to make it so that way it does not overwrite this style. How might I do that?

    <script type="text/javascript">
    function ChangeColor(tableRow, highLight)
    {
    if (highLight)
    {
      tableRow.style.backgroundColor = '#dcfac9';
    }
    else
    {
      tableRow.style.backgroundColor = 'white';
    }
  }

  function DoNav(theUrl)
  {
  document.location.href = theUrl;
  }
  </script>

If you have any better suggestions to accomplish this task I would love to hear them!

My tr tag has a bgcolor tag in it that is set by my php if that specific piece of mail has been read or not.

Upvotes: 0

Views: 1451

Answers (1)

Rick Copeland
Rick Copeland

Reputation: 11922

If the original background color is specified via a stylesheet or (as in your case) a legacy bgcolor attribute, then you can just clear out the style on the element when you're done, and it'll revert:

function ChangeColor(tableRow, highLight)
{
  if (highLight)
  {
    tableRow.style.backgroundColor = '#dcfac9';
  }
  else
  {
    tableRow.style.backgroundColor = '';
  }
}

That said, you'd probably be better off using a CSS class and associated rules to represent the highlighted state of the row and add/remove that as you like:

tr { backgroundColor: <whatever> }
tr.highlighted { backgroundColor: #dcfac9 }

Then your Javascript becomes

function ChangeColor(tableRow, highLight) {
    if(highLight) 
    {
        tableRow.className = 'highlighted';
    } 
    else 
    {
        tableRow.className = '';
    }
}

In addition to keeping specific styles out of your script and markup (where they become difficult to maintain over time), this lets you add or change hover styles (say, bold text, or a border) without adding complexity to the code.

If you have access to a Javascript library such as Prototype, Ext.js or Dojo, then you can use their class manipulation functions instead, which will handle the case where you want to preserve an existing className, or are using multiple classes for on a single element.

Upvotes: 5

Related Questions