wasabicube © 2004

Stripey tables - resources

Description

This source code has an accompanying article describing the use of the Document Object Model (DOM) and JavaScript to add guide stripes to <table> elements.

For a working example, examine the page source for the Waxheadlines.

JavaScript


function tableStripe(p_strId, p_strClass, p_bOdd) {

  var l_Table = document.getElementById(p_strId);

  if(l_Table.rows) {
  // Search through the table for the row elements and 
  // apply the p_strClass to the odd, or even ones depending 
  // on the Boolean p_bOdd
    for(var l_iIndex = 0; l_iIndex < l_Table.rows.length; l_iIndex++) {
      var l_Row = l_Table.rows.item(l_iIndex);
    
      // If the row doesn't already have a class...
      if(!hasClass(l_Row)) {
        if(((l_iIndex%2) == 0) && p_bOdd) {
          l_Row.className = p_strClass;
        }
        else if(((l_iIndex%2) != 0) && !p_bOdd) {
          l_Row.className = p_strClass;
        }
      }
    }
  }
}    


// this function is needed to work around 
// a bug in IE related to element attributes        
function hasClass(p_Element) {
   var l_bRet = false;
   if (p_Element.getAttributeNode("class") != null) {
       l_bRet = p_Element.getAttributeNode("class").value;
   }
   return l_bRet;
}

Optimization! - 15-Mar-2004: Following a suggestion by my friend Nigel, we can make the algorithm more efficient by discarding the modulo arithmetic (of which I was very proud!) and realising (d’oh) that, since we’ve got an ordered list of rows, we can loop through visiting only every second row...

function tableStripe(p_strId, p_strClass, p_bOdd) {

  var l_Table = document.getElementById(p_strId);
  var l_iIndex = ( p_bOdd ? 1 : 0 );

  if(l_Table.rows) {
    for( ; l_iIndex < l_Table.rows.length; l_iIndex += 2) {
      var l_Row = l_Table.rows.item(l_iIndex);

      if( !hasClass(l_Row) ) {
        l_Row.className = p_strClass;
      }
    }
  }
}