Zebra tables

Tagged with Javascript

View as text


/* Zebra-striping tables 
Place this in your <head></head> region of the html doc

<script src="scripts/striping.js"></script>

Looks for all tables with class="datatable" with any specified ID attribute.

*/

addStripingEvent(window, "load", stripe);

function stripe(){

	// don't do anything if you can't grab the body tag of the doc!
	if (document.getElementsByTagName('body')){
		
		var tables, i, rows, r;
		// get all tables
		tables = document.getElementsByTagName('table');
		
		// loop through tables
		for(i=0; i<tables.length ;i++){
			
			// if it's a dataTable then do the work
			if (tables[i].className == 'datatable'){
				// grab the id so you can get the nodes
				table = document.getElementById(tables[i].id);
				// if it worked (standards-based browser)
				if (table){
					rows = table.getElementsByTagName('tr');
					for(r=0; r<rows.length ;r++){
						if(r % 2 == 0){
							rows[r].className = 'even';
						}else{
							rows[r].className = 'odd';
						} // end if
					} // end for
				} // end if
			} // end if
		} // end for
	} // end if

}


function addStripingEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
  if (elm.addEventListener){
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent){
    var r = elm.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
} 





Original snippet written by Brian Hogan
Last updated at 05:39 AM on Jul 07, 2008 by Brian Hogan

SnippetStash costs money to host and develop. The service is free for everyone to use
but if you found it useful please consider making a small donation.