• Home
Pictures Archives Travel RSS

Auto coloring of child nodes using Prototype

19 June 2008 | JavaScript, Prototype | No Comments

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.

Popularity: unranked [?]

« Previous Entry

Next Entry »

Recent Comments

  • Concentratedmedia Blog » Blog Archive » Creating Dynamic iframes for IE 6 & 7, Safari 3, Firefox 2 & 3: [...] this but the best
  • Suneth Mendis: Combining both is a BAD
  • Julks: Hi Suneth, How to put the
  • Suneth Mendis: You are spot on Michael.
  • Michael McLawhorn: I ran into a related

Popular Posts

  • Iframe dynamic resizing… SOLVED!
  • iFrame dynamic resizing revisited
  • Offline blog editor
  • "Fun" with Prototype and IE7 and Tables
  • What!?

About Me

One life, Live it!

My name is Suneth Mendis. I'm a 29 year old Software Engineer. I live in Brisbane Australia and working for a very exciting company called Ephox.

  • Recent Posts

    • Ignorance is your loss
    • Auto coloring of child nodes using Prototype
    • iFrame dynamic resizing revisited
    • Using jQuery with Prototype - Sweet!!!
    • “Fun” with Prototype and IE7 and Tables
    • What serious lack of sleep can do to a developer…
    • iSurprise
    • Offline blog editor
    • What!?
    • Iframe dynamic resizing… SOLVED!
    • more...
  • Categories

    • Agile
    • Blogroll
    • Coding
    • Gadgets
    • Hobbies
    • Ideas
    • JavaScript
    • Life
    • Mac
    • Prototype
    • Travel
    • Work
    • WTF
  • Links

    • Planet Ephox

Copyright © Suneth Mendis 2008 · Designed by Suneth Mendis · Powered by WordPress