howto: alternate list items in a div with javascript

So, TJ and I were trying to figure out a way to get the sidebar on ganb to alternate list item background colors. We did some research on possible CSS classes and pseudo classes but could not figure out a way to do it how we wanted to. So, I set out to create reusable javascript method to take care of this issue.

What I wanted:
1. alternating list item background colors
2. ability to specify which container i wanted to apply this method to (in this case a div).

So, here it is …

1:  <script language="javascript">

2:      function doLoadFunctions() {

3:          setListItemAltColor('test2');

4:      }

5:

6:      function setListItemAltColor (src) {

7:          var divWithLists = document.getElementById(src);

8:

9:          var items = divWithLists.getElementsByTagName('li');

10:          var itemsLength = items.length;

11:

12:          for ( i = 0; i < itemsLength; i++ ) {

13:              if ( i%2 == 0 ) { items[i].style.backgroundColor = "#369"; }

14:          }

15:      }

16:  </script>

I generally have a function that handles all onload javascript events that I call like this: body onload=”doLoadFunctions()”. Within function doLoadFunctions(), simply call function setListItemAltColor (src), whereas src is the container you wish to apply this to. In the example above, the div I want to apply this to is ‘test2’.

There are a few interesting javascript functions I used in this code.
1. if ( i%2 == 0) — checks to see if integer i is odd or even
2. divWithLists.getElementsByTagName(‘tag’) returns a collection of all elements with the specified tag — in this instance it’s all ‘li’ tags.

Download a simple example here.

Enjoy

biz | microsoft has lost it

7 versions of Vista…. 7!!!

Way to go Microsoft. As a techie, I don’t know if i need the Professional Edition or the Enterprise Edition, or the Ultimate version… How the hell is the average PC user supposed to know. I guess whatever you decide to have Dell bundle with their pc’s…

Regardless this is absurd. Either marketing has gotten their dirty hands on this or someone has done some insane market research on versioning and found that if you throw 7 versions of a product at a consumer they will just give up and buy the most expensive.

Starter Edition, Home Basic Edition, Home Premium Edition, Professional Edition, Small Business Edition, Enterprise Edition and Ultimate Edition.

see what everyone else is saying