Hide Table Columns with JavaScript Part 2

22 Mar 2006 by Dan,

When I wrote the originial post about this topic, I had written a quick and dirty function as an experiment. As is the case with most programming, another solution became apparent after digesting the problem for a period of time. So here is a modified solution to the problem:

function toggleCol(strCol){
var ths = document.getElementsByTagName("th");
var tds = document.getElementsByTagName("td");
for (idx in ths){
if (ths[idx].className == strCol)
if (ths[idx].style.display == “none”)
ths[idx].style.display = “table-cell”;
else
ths[idx].style.display = “none”;
}
for (idx in tds){
if (tds[idx].style.display == “none”)
tds[idx].style.display = “table-cell”;
else
tds[idx].style.display = “none”;
}
}

To use the function, just give each of the td’s and th’s in the column the same class name. Then add a link that calls “javascript:hideCol(’columnName’);”. You will also need to define a CSS rule “.hidden {display:none;}”.
This works especially well with scripted table building, such as dumping lots of rows from a database. It makes adding the class name much easier.

Downsides:

  1. The function only hides the column. Now you can toggle the display of the column without a page refresh. Just make sure the link to restore the column is not inside one of the column cells.
  2. The columns re-appear on a page refresh. The next logical step would be to use a cookie to store user the user’s preferences.

5 Comments

  1. Marcel says:

    The clearfix hack could have done all this for you

  2. Dan says:

    Oh Marcel you don’t even know how the clearfix hack works! You told me so! Ha ha.

  3. Tony says:

    Is there anyway to loop though each row of data with an array of states whether it is “none” or “block” ?

  4. Dan says:

    Tony, not sure exactly what you are asking. If you are thinking about hiding some rows when you first build the table then yes you could mark certain td tags with a special class or inline style that would hide them, then create a javascript function and link or button that would un-hide those rows.

  5. Golak Jena says:

    This is very nice.But I am the begiener ,so I could not understand that.

Leave a Reply

More from Dan

Follow Me! Follow Me! Follow Me! Follow Me!
 
 
The Website Grade for www.abdinoor.com!