Auto coloring of child nodes using Prototype

Inspired by David F. Miller's work in 2004 to color alternate table rows (Just like iTunes) I wrote this simple Prototype based script to do the same and a little but more. This script will color any list given that the list belong to a single parent. 

Check out the demo where the script is applied to a table and an unordered list. 

The script 
function Zebra(parentNode, styles) {
    this.colorMe(parentNode, styles);
}

Zebra.prototype = {
    colorMe: function(parentNode, styles) {
        if (parentNode && styles) {
            var styleList = styles.split(",");
            var parents = $$(parentNode);
            for (var i=0; i < parents.length; i++) {
                var currentParent = parents[i];
                var children = currentParent.childElements();
                for (var j=0; j < children.length; j++) {
                    var currentChild = children[j];
                    var k = (j + (styleList.length)) % styleList.length;
                    currentChild.addClassName(styleList[k]);
                }
            }
        }
    }
}
Usage

Usage is pretty simple.

new Zebra(ParentNode, List of styles you like to alternate);

Example
.odd { background: #fff; }
.even { background: #edf3fe;}

new Zebra('ul','odd,even');

The beauty of it is that since its CSS driven, you can have any color imaginable and any number of colors to alternate.


About this entry