JDev

Code, javascript, prototype, jqueryFebruary 26, 2008 3:47 pm

We are going to show how to create lists with alternate colors in Prototype and Jquery.

Let’s say you have an HTML list with with the ‘result‘ id, and you want it to have alternating colors. 

First, create a css class that displays a list item in a different color:

li.alternate { color:green;} 

In Prototype, you use the following syntax:

document.observe(’dom:loaded’ , function(){
    $$(’#result li:nth-child(2n)’ ).invoke(’addClassName’ , ‘alternate’ );
});

Jquery uses the following syntax:

$(document).ready(function(){       
    $("#result li:nth-child(even)").addClass("alternate");           
});

Code, jstlFebruary 21, 2008 8:56 pm

The JSTL iterator exposes  a varStatus variable that holds the loop status. With this information at hand, we can constuct the following JSTL loop to create a list with alternate colors.

<ul>
        <c:forEach var="row" items="${queryResults.rowsByIndex}" varStatus=’vs’>
                 <c:choose>
                 <c:when test= "${vs.index % 2 == 0}">
                         <li class=’even’>
                 </c:when>
                 <c:otherwise>       
                     <li>
                  </c:otherwise>
                  </c:choose>
                       <c:out value="${row[0]}"/>                    
                 </li>
        </c:forEach>
     </ul>

The test condition checks whether the index property of varStatus variable is even or odd, and assigns a css class named ‘even’ to each even item.

You can easily substitute table rows for li elements in this example.