Toggled DIV display state tracking


Posted On: 2008-08-07  



Here are a couple functions to toggle and track a DIVs display state. The only thing you should definitely change in the javascript is the DIV element IDs with its default state that you want to track.

This is probably only a good system for tracking a few (10 or less) DIV states, since it does require a cookie for every DIV.

Here is the javascript...

/* Creat an array of tracked divs and their default state */
var divArray = new Array();

divArray['div1'] = 'none';
divArray['div2'] = 'block';

/*Toggle a DivID block(visable) or none(hidden)*/
function toggleDiv(divid){
   var dv = document.getElementById(divid);

   if (dv != null){
      dv.style.display = (dv.style.display == 'none' ? 'block':'none');
   }
   
   if (divArray[divid]){
      createCookie(divid, dv.style.display, 0);
   }
   return true;
}

/*Create a cookie on a DivID's current state*/
function createCookie(name,value,days) {
   if (days) {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = "; expires="+date.toGMTString();
   }
   else var expires = "";
   document.cookie = name+"="+value+expires+"; path=/";
}

/*Read a cookie so we can set the DivID back to user pref*/
function readCookie(name) {
   var nameEQ = name + "=";
   var ca = document.cookie.split(';');
   for(var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
   }
   return null;
}

/*Reset the DivID's to the users pref if they exist*/
function resetDivs(){
   for (var divName in divArray){
      var dv = readCookie(divName);

      if (dv != null && dv != divArray[divName]){
         toggleDiv(divName);
      }
   }
   return true;
}



For the DIVs you want to toggle and track if necessary, you can use the following to href to do so...

<a href="#" onclick="toggleDiv('div1'); return false;">Hide Me!</a>

<div id="div1">Text to hide!</div>



On every page you are tracking a DIV state use the onload function in the body tag to reset its state if needed...

<body onload="resetDivs()">