Thursday, October 26, 2006

jQuery Tip: Highlight row on hover

This snippet applies a class when you hover over a table row and removes it when you move the mouse out. Useful when you have a table with many rows and want to improve readability.

Define your stylesheet in head:

<style type="text/css">
<!--
 #mytable {
  border-collapse: collapse;
  width: 300px;
 }
 #mytable th,
 #mytable td
 {
  border: 1px solid #000;
  padding: 3px;
 }
 #mytable tr.highlight {
  background-color: #eee;
 }
//-->
</style>

JavaScript (also in head)

<script type="text/javascript">
<!--
$(
 function()
 {
  $("#mytable tr").hover(
   function()
   {
    $(this).addClass("highlight");
   },
   function()
   {
    $(this).removeClass("highlight");
   }
  )
 }
)
//-->
</script>

Your table (with id mytable) in body

<table id="mytable">
 <tr>
  <th>Foo</th>
  <td>Lorem</td>
  <td>Ipsum</td>
 </tr>
 <tr>
  <th>Bar</th>
  <td>Dolor</td>
  <td>Sit</td>
 </tr>
 <tr>
  <th>Baz</th>
  <td>Amet</td>
  <td>Consectetuer</td>
 </tr>
</table>

Now whenever you move your mouse over a row in the table, the background colour is changed to gray (#eee is a shade of gray).

4 comments:

Anonymous said...

what's wrong with tr:hover?

Jon said...

Hi.

Just getting to grips with jQuery. How would you do this if the tr already had a class, doesn't seem to work in this case?

Jon

Sam said...

tr:hover could apply the class when you hover over it, but how would you then remove it when you mouse out?
$("#mytable tr:hover").addClass("highlight")

Also, you may want to do things as well as adding a class (e.g. showing fields).

If the tr already has a class it should still work (unless the class is named 'highlight').

Anonymous said...

I believe you need this because IE6 doesn't recognize tr:hover.