View Full Version : Toggling Visibility

12-23-2006, 09:52 PM
How can I use javascript to toggle the visibility of a whole column of a table?
For example, I click a link on the top of the page, and the column is shown or becomes invisible, and this works for every column, with a different link to click on.


Edit: I've found a way to do it, but I'm not sure it's the 'best' way...

<script type="text/javascript">

function toggle_visibility(id) {
var inc=0
var alltags=document.all? document.all : document.getElementsByTagName("*")
for (i=0; i<alltags.length; i++){
if (alltags[i].className==id)
if(alltags[i].style.display == 'none')
alltags[i].style.display = '';
alltags[i].style.display = 'none';

I am using that toggle function on links, like so:

<b><a href="#" onclick="toggle_visibility('dummy1');">Dummy 1</a></b>

Then, On each table cell, I have a div that has the class 'dummy1', like this:

<td><div class="dummy1">Dummy 1</div></td>
<td><div class="dummy2">Dummy 2</div></td>
<td><div class="dummy3">Dummy 3</div></td>
<td><div class="dummy4">Dummy 4</div></td>

Is there an easier way of doing it by column, and not by table cell?


12-24-2006, 12:05 AM
The correct method of doing this is to use the CSS2 visibility: collapse declaration on a col or colgroup element. Unfortunately, Internet Explorer doesnít support it and Opera only supports it superficially. Firefox does support it, but it seems to have an issue refreshing alignment of cell content.

Hereís an example that that collapses the second column when you click the table and shows the column again when you click the table once more. Of course, youíll only see the effect in Firefox. Note that the table header doesnít align correctly when the column is collapsed; I believe that thatís a Firefox bug.

For reference, the Firefox issue is Bug 354846 (https://bugzilla.mozilla.org/show_bug.cgi?id=354846).

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="Author" content="Patrick Garies"/>
<title>CF 103629 Demo</title>

<style type="text/css">
table {
margin: 0 auto;
table-layout: fixed;
text-align: center;
font-family: Verdana, sans-serif;
col {
width: 200px;
col.collapse {
visibility: collapse;
th, td {
border: 1px solid;
padding: 0.5em;

<script type="text/javascript">
document.defaultView.addEventListener("load", function() {
document.getElementsByTagName("table")[0].addEventListener("click", function() {
var column = document.getElementsByTagName("col")[1];
if (document.defaultView.getComputedStyle(column, "").visibility == "visible") column.className = "collapse";
else column.className = "";
}, false);
}, false);


<table xml:lang="ja" lang="ja">
<th colspan="3">Rōmaji <span xml:lang="en" lang="en">Numbers</span></th>