Alternating Background Colors

Summary

This script allows me to automatically alternate two different background colors to a series of the same tag, like the <li> list item tag.

I made the script where I have control over the two colors separate from within the script so I can apply the same script to different items with different colors.

I made this while working on the design for Flush, my design blog, trying to alternate the background color of numerous lists on the sidebar.

Example

Date Created

Nov 2007.

Help

  1. I made this in late 2007 and did not record all the places I went to to make this script, but I know I did a lot of referencing with w3schools.com.
  2. And I also found a script by Robert Nyman that selects items by class names.

Process

Didn't record the process at the time, although it took a lot of trial and error. I found a script that lets you select items by class name, where JavaScript does not inherently support. I also learned how to use the for loop.

  1. Test page.

The Code

Here’s the code. Please link back here if you’re using it.

Put this JavaScript in the head tag.

function altBG(listId,oddItem,evenItem){

var listItem=document.getElementById(listId).getElementsByTagName("li");

for (var i=0;i<listItem.length;i++){
if (i%2==1){ // if the item is odd (remainder is 1)
listItem[i].style.backgroundColor=oddItem;
} else if (i%2==0){ //if the item is even (remainder is 0)
listItem[i].style.backgroundColor=evenItem;
}
}
}

/* HOW TO USE:

listId: id of list
oddItem: the background color of the odd-numbered items, set in quotes and hexidecimals
evenItem: the background color of the even-numbered items, set in quotes and hexidecimals

*/

Put this HTML in the body tag.

<div id='div1' >
    <ul id='ul-list' >
        <li id='listId1' class='list-item' >blah1</li>
        <li class='list-item' >blah2</li>
        <li class='list-item' >blah3</li>
        <li class='list-item' >blah4</li>
        <li class='list-item' >blah5</li>
        <li class='list-item' >blah6</li>
        <li class='list-item' >blah7</li>
    </ul>
</div>

Put this JavaScript in body tag, after the list.

altBG("ul-list","#ccddee","#eeddcc");

Return to top