faqts : Computers : Programming : Languages : JavaScript : DHTML

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

183 of 262 people (70%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How to show and hide a table with DHTML and CSS?
How to setup cookies in order to remember hide / unhide DHTML Table user preference ?

Jun 24th, 2003 14:19
Andrew Cranwell, Steven Groot, Stan Jester, Russ Locke, HPROD PROD,


Hi,
I have noticed that you seem to be using only the visibility command 
available to you in css. There is also the 'display' style tag. You can 
specifiy display: block or display: none to completely show/hide any 
element (at least within IE5.5+/NS6.2+). You must specify a style 
element / class attribute in your tag for this to work. You can still 
work with absolute / relative positioning and the neat thing is that 
you don't have to worry about any z-indexes or div layers to muck up 
your positioning within a page.
I don't have any answer to the cookie issue, however, but maybe you can 
combine other answers!
E.g.
<html>
<!-- Andrew Cranwell / http://www.factum.co.uk -->
<head>
<script>
function show(obj) {
  eval("document.all." + obj + ".style.display='block'");
}
function clearIt(obj) {
  eval("document.all." + obj + ".style.display='none'");
}
</script>
</head>
<body>
<div style="display: block" id="show1">
<table border="1"><tr><td>Hello</td></tr></table>
</div>
<br>
<input type="button" onclick="show('show1')" name="show" value="Show">
<input type="button" onclick="clearIt('show1')" name="clear" 
value="Clear">
</body>
</html>
This is the improved version of the code below the line. This code 
also has the support for remembering the choice of the user (show or 
hide the table).
<html>
<head>
 <style type="text/css">
 .collapse { position: absolute; visibility: hidden; }
 .expand { position: relative; visibility: visible; }
 </style>
<SCRIPT LANGUAGE="JavaScript">
	<!-- Original:  Bill Dortch, Idaho Design ([email protected])
	<!-- This script and many more are available free online at -->
	<!-- The JavaScript Source!! http://javascript.internet.com -->
	<!-- Begin
	function getCookieVal (offset) {
		var endstr = document.cookie.indexOf (";", offset);
		if (endstr == -1)
			endstr = document.cookie.length;
		return unescape(document.cookie.substring(offset, 
endstr));
	}
	function GetCookie (name) {
		var arg = name + "=";
		var alen = arg.length;
		var clen = document.cookie.length;
		var i = 0;
		while (i < clen) {
			var j = i + alen;
			if (document.cookie.substring(i, j) == arg)
				return getCookieVal (j);
			i = document.cookie.indexOf(" ", i) + 1;
			if (i == 0) break; 
		}
		return null;
	}  
	function SetCookie (name, value) {
		var argv = SetCookie.arguments;
		var argc = SetCookie.arguments.length;
		var expires = (argc > 2) ? argv[2] : null;
		var path = (argc > 3) ? argv[3] : null;
		var domain = (argc > 4) ? argv[4] : null;
		var secure = (argc > 5) ? argv[5] : false;
		document.cookie = name + "=" + escape (value) +
			((expires == null) ? "" : ("; expires=" + 
expires.toGMTString())) +
			((path == null) ? "" : ("; path=" + path)) +
			((domain == null) ? "" : ("; domain=" + 
domain)) +
			((secure == true) ? "; secure" : "");
	}
	// End -->
	</SCRIPT>
	<script type="text/javascript" language="javascript">
	var tableVisible = GetCookie('tablestatus');	//While 
loading the page, get the cookie-value
	function SetTableStatus() {
		var expdate = new Date ();
		expdate.setTime (expdate.getTime() + (24 * 60 * 60 * 
1000 * 31));
		SetCookie ("tablestatus", tableVisible, expdate);
	}
	function toggletable() {
		var temp = document.getElementById('thistable');
		if (tableVisible=="true") {		//if true, 
table is visible so hide it
			tableVisible = "false";
			temp.style.position = 'absolute';
			temp.style.visibility = 'hidden';
		} else {				//table is not 
visible, so expand it.
			tableVisible = "true";
			temp.style.position = 'relative';
			temp.style.visibility = 'visible';
		}
		SetTableStatus();
	}
	function togglefirst() {
		var temp = document.getElementById('thistable');
		if(tableVisible=="true") {	//Previous time stored 
as visible, so show the table
			temp.style.position = 'relative';
			temp.style.visibility = 'visible';
		} else {				
	//Previous time stored as hidden, so hide the table
			temp.style.position = 'absolute';
			temp.style.visibility = 'hidden';
		}
	}
	</script>
</head>
<body onload="togglefirst();"><!-- after loading is complete, start 
this function -->
 <table bgcolor="#FFCC99" width="600" cellspacing=0 border=0>
 <tr>
  <td>
  <p><a href="javascript:toggletable();">toggle a table 
visible/invisible</a>
  </td>
 </tr>
 </table>
 <div>
 <table bgcolor="#FFFFCC" width="300" cellspacing=0 border=0 
id="thistable">
  <tr>
  <td>
   <b>Toggle Table:</b><br> Here is the content of a table which hides 
and shows.
  </td>
  </tr>
 </table>
 </div>
 <table bgcolor="#FFCC99" width="600" cellspacing=0 border=0>
 <tr>
  <td>
  <p>Filler
  </td>
 </tr>
 </table>
</body>
</html>
===============================================================
===============================================================
This works in NS6. However for IE5 only the hide function works. The 
show function does not; it will do one style or the other but not both.
Hopefully somebody can suggest a workaround.
<html>
<head>
 <style type="text/css">
 .collapse { position: absolute; visibility: hidden; }
 .expand { position: relative; visibility: visible; }
 </style>
 <script type="text/javascript" language="javascript">
 var tableToggle = false;
 function toggletable() {
  var temp = document.getElementById('thistable');
  if (tableToggle) {
  tableToggle = false;
  temp.style.position = 'absolute';
  temp.style.visibility = 'hidden';
  } else {
  tableToggle = true;
  temp.style.position = 'relative';
  temp.style.visibility = 'visible';
  }
 }
 </script>
</head>
<body>
 <table bgcolor="#FFCC99" width="600" cellspacing=0 border=0>
 <tr>
  <td>
  <p><a href="javascript:toggletable();">toggle a table 
visible/invisible</a>
  </td>
 </tr>
 </table>
 <div>
 <table bgcolor="#FFFFCC" width="300" cellspacing=0 border=0 
id="thistable" class="collapse">
  <tr>
  <td>
   <b>Toggle Table:</b><br> Here is the content of a table which hides 
and shows.
  </td>
  </tr>
 </table>
 </div>
 <table bgcolor="#FFCC99" width="600" cellspacing=0 border=0>
 <tr>
  <td>
  <p>Filler
  </td>
 </tr>
 </table>
</body>
</html>
-----------------------------------------------------------------------
If have tested your code, and it doesn't work with the id 'thistable' 
set in the <div>. I Have put that id in the <table>-tag and it works 
fine under IE5.5 and Mozilla 1.1
-----------------------------------------------------------------------
You can dynamically rebuild the table.  I do it here in my sort ...
<head>
	<title>Accounting Tool</title>
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
function setDataType(cValue)
  {
	// Take out '$' so money is sorted like numbers and not strings
  	cValue = cValue.replace("\$", "")
    // THIS FUNCTION CONVERTS DATES AND NUMBERS FOR PROPER ARRAY
    // SORTING WHEN IN THE SORT FUNCTION
    var isDate = new Date(cValue);
    if (isDate == "NaN")
      {
        if (isNaN(cValue))
          {
            // THE VALUE IS A STRING, MAKE ALL CHARACTERS IN
            // STRING UPPER CASE TO ASSURE PROPER A-Z SORT
            cValue = cValue.toUpperCase();
            return cValue;
          }
        else
          {
            // VALUE IS A NUMBER, TO PREVENT STRING SORTING OF A NUMBER
            // ADD AN ADDITIONAL DIGIT THAT IS THE + TO THE LENGTH OF
            // THE NUMBER WHEN IT IS A STRING
            var myNum;
            myNum = String.fromCharCode(48 + cValue.length) + cValue;
            return myNum;
          }
        }
  else
      {
        // VALUE TO SORT IS A DATE, REMOVE ALL OF THE PUNCTUATION AND
        // AND RETURN THE STRING NUMBER
        //BUG - STRING AND NOT NUMERICAL SORT .....
        // ( 1 - 10 - 11 - 2 - 3 - 4 - 41 - 5  etc.)
        var myDate = new String();
        myDate = isDate.getFullYear() + " " ;
        myDate = myDate + isDate.getMonth() + " ";
        myDate = myDate + isDate.getDate(); + " ";
        myDate = myDate + isDate.getHours(); + " ";
        myDate = myDate + isDate.getMinutes(); + " ";
        myDate = myDate + isDate.getSeconds();
        //myDate = String.fromCharCode(48 + myDate.length) + myDate;
        return myDate ;
      }
  }
function sortTable(col, tableToSort)
  {
    var iCurCell = col + tableToSort.cols;
    var totalRows = tableToSort.rows.length;
    var bSort = 0;
    var colArray = new Array();
    var oldIndex = new Array();
    var indexArray = new Array();
    var bArray = new Array();
    var newRow;
    var newCell;
    var i;
    var c;
    var j;
    // ** POPULATE THE ARRAY colArray WITH CONTENTS OF THE COLUMN 
SELECTED
    for (i=1; i < tableToSort.rows.length; i++)
      {
        colArray[i - 1] = setDataType(tableToSort.cells
(iCurCell).innerText);
        iCurCell = iCurCell + tableToSort.cols;
      }
    // ** COPY ARRAY FOR COMPARISON AFTER SORT
    for (i=0; i < colArray.length; i++)
      {
        bArray[i] = colArray[i];
      }
    // ** SORT THE COLUMN ITEMS
    //alert ( colArray );
    colArray.sort();
    //alert ( colArray );
    for (i=0; i < colArray.length; i++)
      { // LOOP THROUGH THE NEW SORTED ARRAY
        indexArray[i] = (i+1);
        for(j=0; j < bArray.length; j++)
          { // LOOP THROUGH THE OLD ARRAY
            if (colArray[i] == bArray[j])
              {  // WHEN THE ITEM IN THE OLD AND NEW MATCH, PLACE THE
                // CURRENT ROW NUMBER IN THE PROPER POSITION IN THE
                // NEW ORDER ARRAY SO ROWS CAN BE MOVED ....
                // MAKE SURE CURRENT ROW NUMBER IS NOT ALREADY IN THE
                // NEW ORDER ARRAY
                for (c=0; c<i; c++)
                  {
                    if ( oldIndex[c] == (j+1) )
                    {
                      bSort = 1;
                    }
                      }
                      if (bSort == 0)
                        {
                          oldIndex[i] = (j+1);
                        }
                          bSort = 0;
                        }
          }
    }
  // ** SORTING COMPLETE, ADD NEW ROWS TO BASE OF TABLE ....
  for (i=0; i<oldIndex.length; i++)
    {
      newRow = tableToSort.insertRow();
      for (c=0; c<tableToSort.cols; c++)
        {
          newCell = newRow.insertCell();
          newCell.innerHTML = tableToSort.rows(oldIndex[i]).cells
(c).innerHTML;
        }
      }
  //MOVE NEW ROWS TO TOP OF TABLE ....
  for (i=1; i<totalRows; i++)
    {
      tableToSort.moveRow((tableToSort.rows.length -1),1);
    }
  //DELETE THE OLD ROWS FROM THE BOTTOM OF THE TABLE ....
  for (i=1; i<totalRows; i++)
    {
      tableToSort.deleteRow();
    }
  //Make every other background whitesmoke ....
  for (i=0; i<totalRows; i = i + 2)
    {
     tableToSort.tBodies[1].rows[i].style.background = "WhiteSmoke";
    }
  }
//  End -->
</script>
</head> 
<body>
							<TABLE 
WIDTH="97%" BORDER=0 CELLSPACING=0 CELLPADDING=5 name="rsTable1" 
id=rsTable1 cols=6>
								<TR>
	<TD width=123 align="left"><A href="javascript:sortTable(0, 
rsTable1);"><font size='-2' color='##000066' 
face='Verdana'><b>Sort</FONT></B></A></TD>
	<TD width=78  align="right"><A href="javascript:sortTable(1, 
rsTable1);"><font size='-2' color='##000066' 
face='Verdana'><b>Sort</FONT></B></A></TD>
	<TD width=53  align="right"><A href="javascript:sortTable(2, 
rsTable1);"><font size='-2' color='##000066' 
face='Verdana'><b>Sort</FONT></B></A></TD>
	<TD width=118 align="right"><A href="javascript:sortTable(3, 
rsTable1);"><font size='-2' color='##000066' 
face='Verdana'><b>Sort</FONT></B></A></TD>
	<TD width=53  align="right"><A href="javascript:sortTable(4, 
rsTable1);"><font size='-2' color='##000066' 
face='Verdana'><b>Sort</FONT></B></A></TD>
	<TD 		  align="center"><A href="javascript:sortTable
(5, rsTable1);"><font size='-2' color='##000066' 
face='Verdana'><b>Sort</FONT></B></A></TD>
								</TR>
								<TBody>
	<cfloop 
collection=#RepName# item="KeyValue">
	<tr>
		<td><font size="-1" color="##000000" 
face="Verdana">#StructFind(RepName, KeyValue)#</font></td>
		<td><font size="-1" color="##000000" face="Verdana"><p 
align="right">$#StructFind(NewBusiness, KeyValue)#</font></td>
		<td><font size="-1" color="##000000" face="Verdana"><p 
align="right">$#StructFind(Renewals, KeyValue)#</font></td>
		<td><font size="-1" color="##000000" face="Verdana"><p 
align="right">$#StructFind(AccountsReceivable, KeyValue)#</font></td>
		<td><font size="-1" color="##000000" face="Verdana"><p 
align="right">$#StructFind(RepTotal, KeyValue)#<font></td>
		<td><font size="-1" color="##000000" face="Verdana"><p 
align="right">#StructFind(RepTeamLeader,KeyValue)#</font></td>
	</tr>
	</cfloop>
	</TBody>
							</TABLE>
</body>