Friday, July 18, 2008

jQuery Alternating Row Highlighter Example

Again, another simple use of jQuery to highlight rows in a table, but this example keeps the different classes for alternating table rows intact. Again, I'm still learing, I bet there is some kind of xpath test for values that can cut down the size of the javascript.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<title>Alternating Highlights</title>
<script src="../s/jquery-1.2.6.pack.js" type="text/javascript">
</script>
<style type="text/css">
.r0 {background-color:White;color:Black}
.r1 {background-color:#f5f5f5;color:Black}
.hl {background-color:Yellow;color:red;cursor: hand}
</style>
</
head>
<
body>
<
p>
jQuery alternating highlight example.
</p>
<
table id="test" border="1" rules="none" cellspacing="0"
style="border: solid 2px navy">
<
tr class="r0">
<td>some data</td>
<td>some data</td>
</
tr>
<
tr class="r1">
<td>some other data</td>
<td>some other data</td>
</
tr>
<
tr class="r0">
<td>some data</td>
<td>some data</td>
</
tr>
<
tr class="r1">
<td>some other data</td>
<td>some other data</td>
</
tr>
<
tr class="r0">
<td>some data</td>
<td>some data</td>
</
tr>
<
tr class="r1">
<td>some other data</td>
<td>some other data</td>
</
tr>
<
tr class="r0">
<td>some data</td>
<td>some data</td>
</
tr>
<
tr class="r1">
<td>some other data</td>
<td>some other data</td>
</
tr>
</
table>
<
script language="javascript" type="text/javascript">
$(document).ready(function() {
$(
"#test").find("tr[@class='r0']").each(
function()
{
$(
this).hover(function() {
$(
this).addClass("hl");
},
function(){
$(
this).removeClass("hl");
$(
this).addClass("r0");
});
});
$(
"#test").find("tr[@class='r1']").each(
function()
{
$(
this).hover(function() {
$(
this).addClass("hl");
},
function(){
$(
this).removeClass("hl");
$(
this).addClass("r1");
});
});
});
</script>
</
body>
</
html>

No comments: