Add striped styling to a list of items

Mike Flynn picture Mike Flynn · Jun 22, 2011 · Viewed 9.7k times · Source

What would be the best way to stripe a list with KnockoutJS? The class on the div below should be even or odd depending where it is in the list, and update when adding or removing items.

<div class="Headlines loader" 
     data-bind="css: { loader: headlines().length == 0 }, 
                       template: { name: 'recentHeadlinesTemplate',
                                   foreach: beforeHeadlineAddition, 
                                   beforeRemove: function(elem) { $(elem).slideUp() },
                                   afterAdd: slideDown }">
</div>

<script type="text/html" id="recentHeadlinesTemplate">
    <div class="even">
        ${Title}
    </div>  
</script>

Answer

ZiglioUK picture ZiglioUK · Jun 12, 2012

I've found a function that returns an index when iterating with foreach, so you can apply even and odd classes in a reasonably compact way, for example:

<tr data-bind="css: { 'even': ($index() % 2 == 0) }">