jQuery Code Example: Using the Zebra Method



Here is a simple example of how to shade alternating items in an ordered list using the Zebra method, then highlight each item with a color as the mouse rolls over it. You'll need 3 files: an HTML, a .css, and a .js First, the HTML:

Code:

<html>
<head>
<title>
Zebra Example
</title>
<link href="zebra.css" type="text/css" rel="stylesheet">
</head>
<body>
<div>
<ol>
<li class="line">Here is a list item</li>
<li class="line">Here is another list item...</li>
<li class="line">And another...</li>
<li class="line">And another...</li>
<li class="line">And another...</li>
<li class="line">And another...</li>
<li class="line">And another!</li>
<li class="line">Roll over the list items to see what happens.</li>
</ol>
</div>
<script src="libs/jquery-1.4.4.js"></script>
<script src="highlighting.js"></script>
</body>
</html>

Then, the .css:

Code:

* {
margin: 3;
padding: 3;
}

body {
background-color: #ffffff;
color: #000000;
font-family: sans-serif;
font-size: 1em;
line-height: 1.65;

}

li.line {
list-style-type: none;
border-top-style: dotted;
border-top-width: 1px;
clear: both;
padding-bottom: 2px;
padding-top: 2px;
position: relative;
width: 66%;
}

.zebra {
background-color: #EFEFEF;
}

.zebraOver {
background-color: #F6CECE;
}

Then the .js:

Code:

$(document).ready(function() {
$('.line:odd').addClass('zebra');

$('.line').hover(
function() { // mouseover
$(this).addClass('zebraOver');
},
function() { // mouseout
$(this).removeClass('zebraOver');
}
);
});

Note the names of the .js & .css files in the HTML code.

Published April 7, 2011