Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Showing / hiding table columns

Tables ehancement

Showing / hiding table columns

by  BillyRayPreachersSon  Posted    (Edited  )
This snippet shows you how to toggle entire columns on/off by clicking the table header.

It in no way stops data being presented to those without JavaScript enabled.

Assigning any table a class of "collapseColumns" will automatically attach this "collapsible" behaviour to the table when the page loads.

By default, all data is hidden. To switch this so that the data starts visbile, change the visibility property in the style sheet from "hidden" to "visible".

I've tested this solution in IE6 and FireFix 0.8, and it works fine. It should work in most other browsers, too.

Code:
<html>
<head>
	<style type="text/css">
		table.collapseColumns td {
			visibility: hidden;
		}
	</style>

	<script type="text/javascript">
	<!--
		function setupTables() {
			var tables = document.getElementsByTagName('table');
			for (var tableLoop=0; tableLoop<tables.length; tableLoop++) {
				if (tables[tableLoop].className == 'collapseColumns') {
					var headerRow = tables[tableLoop].tHead.rows[0].cells;
					for (var cellLoop=0; cellLoop<headerRow.length; cellLoop++) {
						headerRow[cellLoop].onclick = toggleColumn;
						headerRow[cellLoop].style.cursor = 'pointer';
					}
				}
			}
		}

		function toggleColumn() {
			var table = this.parentNode.parentNode.parentNode;
			var columnNumber = this.cellIndex;
			var isShowing = (table.tBodies[0].rows[0].cells[columnNumber].style.visibility == 'visible');

			var rows = table.tBodies[0].rows;
			for (var rowLoop=0; rowLoop<rows.length; rowLoop++) {
				rows[rowLoop].cells[columnNumber].style.visibility = isShowing ? 'hidden' : 'visible';
			}
		}
	//-->
	</script>
</head>
<body onload="setupTables();">
	<table border="1" class="collapseColumns">
		<thead>
			<tr>
				<th>Column 1</th>
				<th>Column 2</th>
				<th>Column 3</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td>Cell 1, 1</td>
				<td>Cell 1, 2</td>
				<td>Cell 1, 3</td>
			</tr>
			<tr>
				<td>Cell 2, 1</td>
				<td>Cell 2, 2</td>
				<td>Cell 2, 3</td>
			</tr>
			<tr>
				<td>Cell 3, 1</td>
				<td>Cell 3, 2</td>
				<td>Cell 3, 3</td>
			</tr>
		</tbody>
	</table>
</body>
</html>

Dan


[link http://www.coedit.co.uk/][color #00486F]Coedit Limited[/color][/link][color #000000] - Delivering standards compliant, accessible web solutions[/color]

[tt]Dan's Page [blue]@[/blue] Code Couch
http://www.codecouch.com/dan/[/tt]
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top