I would really appreciate some help with this. I have searched and searched the internet but cannot find information on exactly what I am trying to do. I have a javascript toggle function:

function toggle_change() {
	var ele = document.getElementById("change_log");
	var text = document.getElementById("Toggle_change");
	if(ele.style.display == "none") {
    		ele.style.display = "block";
		text.innerHTML = "-";
  	}
	else {
		ele.style.display = "none";
		text.innerHTML = "+";
	}
}

What I am trying to do is set a cookie that will remember if the display status is "none". This is probably something simple but I don't know much about javascript obviously. I've tried a few different approaches but I can never get the script to actually set a cookie. Thanks for your assistance.

Hi,

i'll provide you with some example later.

I just post back when im done to it.

-essential

As an answer is promised, I won't butt in. Instead, I'll give some tidbits as reminders to how the web works.

Generally speaking, cookies are sent between the server and the browser by way of HTTP headers. To send a cookie to the server, the browser must form the cookie and place it into the HTTP headers.

Cookies are stored in the DOM for easy access via document.cookie. So your ECMAScript needs to create a cookie in the current document in order for it to be sent to the server when a form is submitted.

Finally, remember that you are working with three different, separate things here: HTTP communication protocol, HTML layout language and ECMAScript programming language. The three are separate, can interact and communicate, but extra effort is often needed for things to 'work'. Oh, I forgot to mention the server side, which requires even more stuff for interaction and communication.

I think once you grok the segregation and separation, it'll be a lot clearer how to do things on the browser. It isn't rocket science, but it can be a chorekeeping track of what you are doing and where you are doing it. But once you get the knack of it, you'll be wondering why it took you so long to learn it.

A good reference book is O'Reilly's Javascript tome by David Flanagan. I'm currently using the 5th edition (printed 8/2006).

Hi Tekkno,

but if you still want to claim things with cookies.

Then here is my demo:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<?xml-stylesheet type="text/css" href="./images/main.css" media="screen"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html id="xhtml10" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://www.w3.org/2005/10/profile">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<title>http://www.daniweb.com/</title>
<script type="text/javascript">
// <![CDATA[

/******************************

 * Developed by DANIuser : essential ~
 * This notice must stay intact for use - 
 * http://www.daniweb.com/forums/member383844.html

******************************/

var doc = ( document );
var Session = function( name, value, expires, path, domain, secure ) {
var today = new Date();
   today.setTime( today.getTime() );
   if ( expires ) {
      this.expires = ( expires  * ( 1000 * 60 * 60 * 24 ));
      this.willExpire = new Date( today.getTime() + ( this.expires ));
   } else {
      this.willExpire = new Date( today.getTime() + ( 365  * 1000 * 60 * 60 * 24 ));
   }
   this.name = name || "";
   this.value = value || "";
   this.path = path || "";
   this.domain = domain || "";
   this.secure = secure || "";
   this.getSession = ( function( name ) {
      var extract;
      var val;
      if ( name ) {
         try {
            val = doc.cookie.match("(^|;) ?" + name + "=([^;]*)(;|$)");
            extract = ( RegExp.$2 );
         } catch( d ) {
           val = doc.cookie.indexOf( String( name + "=" ));
            if ( val !== -1 ) {
               val += ((( val ) + name.length ) + 1 );
               var colon = document.cookie.indexOf( ";", val );
               (( colon !== -1 ) ? colon = document.cookie.length : colon = "" );
               extract = document.cookie.substr( val, colon );
            } else { 
               extract = 0;
            } 
         }
      } return (( extract ) ? unescape( extract ) : "" );
   } );
      this.createSession = ( function( name, value, expires, path, domain, secure ) {
         try { 
         var session = name + "=" + escape( value );
         session += "; expires=" + expires.toGMTString();
         session += "; path=" + escape( path );
         session += "; domain=" + domain;
         session += secure;
         document.cookie = session;
         } catch( e ) { 
      } 
   } )( this.name, this.value, this.willExpire, this.path, this.domain, this.secure );
   };

Session.prototype.destroySession = function( name ) {
   this.name = "";
   document.cookie = name + "=" + ";path=" + this.path + ";domain=" + this.domain + ";expires=Thu, 01-Jan-1970 00:00:00 GMT"; 
   }; var $ = function( name, value, expires, path, domain, secure ) {
   if ( arguments.length >= 2 ) {
      new Session( name, value, expires, path, domain, secure ); 
      return;
   } else {
      return false; } // [ Exit Session ]
} 
var displayStatus = 0;
var element = ( function( ids ) {
var ids = (( ids = document.getElementById( ids )) ? ids : ids ) || 0;
   return ids;
} );
var toggle_change = ( function( ele ) {
var ele = element( ele ) || element("change_log");
var text = element("Toggle_change");

 (( ele.style.display === "none" ) ? (( ele.style.display = "block" ) && ( text.innerHTML = "<b>-</b>" )) : (( ele.style.display = "none" ) && ( text.innerHTML = "<b>+</b>" )));

   $( ele.id, ele.style.display ); // Saving status display in cookie session.
   $( text.id, text.innerHTML ) // Saving the content of text element.  
} );
onload = ( function( state ) {
var state = state || 0;
   return function() {
   var statusDisplay;
   var elem = element("change_log");
   var txt = element("Toggle_change");
      if( statusDisplay = state.getSession( elem.id )) {
         elem.style.display = statusDisplay;
         txt.innerHTML = state.getSession( txt.id ); 
         return;
      } return false;
   }
} )( new Session() )
// ]]>
</script>
</head>
<body>
<div id="Toggle_change" onclick="toggle_change(); "><b>-</b></div>
<div id="change_log"><h1>JavaScript Live Demo!</h1></div>

</body>
</html>

hope it helps...

Hi Fest3er,

sorry I didn't noticed that you had a post. Just like to add in some comment --- that your post is very useful for the other viewers' of daniweb.com.

Especially for those people, who are interested to dig in, in the world of JavaScript.

Regards
-essential

Thank you essential, it worked like a charm. And thank you for the info Fest3er, I will have to pick that book up. Javascript is a difficult language to learn with just bits and pieces off the internet. But is all that code really necessary for a simple cookie? No wonder I couldn't figure it out lol. I have a similar javascript which I would like to set a cookie for as well. It does the same thing, but toggles an array instead of a single element. Could I use the same script? I can post it if you like. Thanks again.

Hi Tekkno,

it has some functionality, that you might not need right now, but will be able to help you for future use.

I'l give you the instruction manual, when i get home...
-essential

@Tekkno,

that would be very helful if you can post your code.

Claim this as a normal part of your .js files'

then reference it via <script type="text/javascript" src="./cookie.js"></script> tag.

cookie.js

/* 
~ INSTRUCTION MANUAL ~

 Session - argument & method reference:
 |
 | + Session(  argument lists:
   * name : cookie-name ( string ) #required# -
   * value : cookie-value ( string / number ) #required# -   
   * expires : cookie-expiration ( specify the number of days before expiration ( number )) #optional# -
   - path : cookie-path ( only documents' on this path will be able to retrieve this cookie ( string )) #optional# -
   - domain : domain-address ( only website in this domain will be able to retrieve the cookie. http://www.yourdomain.com/ ( string )) #optional#
   - secure : secured-access ( indicates the browser to use SSL when sending the cookie to the server. ( string / number ) just keep this empty if you don't want to activate this feature ) #optional# -
    ______________
    USAGE EXAMPLE:
   < =============== >
   #1. var mySession = new Session( "someName", "someValue", 31, "/", "http://domainame.com", 1 );
   < =============== >

  | + getSession( 
    * name : cookie-name ( use this method if you want to retrieve cookie values' ( string )) #required# )
    ______________
    USAGE EXAMPLE:
   < =============== >
   #1. var mySession = new Session( "someName", "someValue", 31, "/", "http://domainame.com", true );
   #2. alert( mySession.getSession( "someName" )); // Will output "someValue"
   < =============== > 

  | + destroySession( 
    * name : cookie-name ( gives you the ability to delete cookie with your specified name ( string )) #required# )
    ______________
    USAGE EXAMPLE:
   < =============== >
   #1. var mySession = new Session( "someName", "someValue", 31, "/", "http://domainame.com", true );
   #2. alert( mySession.getSession( "someName" )); // Will output "someValue"
   #3. mySession.destroySession( "someName" ); // clears up the value of the cookie( someName ).
   #4. alert( mySession.getSession("someName")); // Will return empty string.
   < =============== > 
----------------------------------------
 More free script at:
- http://www.daniweb.com
----------------------------------------
*/

var Session = function( name, value, expires, path, domain, secure ) {
var today = new Date();
   today.setTime( today.getTime() );
   if ( expires ) {
      this.expires = ( expires  * ( 1000 * 60 * 60 * 24 ));
      this.willExpire = new Date( today.getTime() + ( this.expires ));
   } else {
      this.willExpire = new Date( today.getTime() + ( 365  * 1000 * 60 * 60 * 24 ));
   }
   this.name = name || "";
   this.value = value || "";
   this.path = path || "";
   this.domain = domain || "";
   this.secure = secure || "";
   this.getSession = ( function( name ) {
      var extract;
      var val;
      if ( name ) {
         try {
            val = document.cookie.match("(^|;) ?" + name + "=([^;]*)(;|$)");
            extract = ( RegExp.$2 );
         } catch( d ) {
           val = document.cookie.indexOf( String( name + "=" ));
            if ( val !== -1 ) {
               val += ((( val ) + name.length ) + 1 );
               var colon = document.cookie.indexOf( ";", val );
               (( colon !== -1 ) ? colon = document.cookie.length : colon = "" );
               extract = document.cookie.substr( val, colon );
            } else { 
               extract = 0;
            } 
         }
      } return (( extract ) ? unescape( extract ) : "" );
   } );
      this.createSession = ( function( name, value, expires, path, domain, secure ) {
         try { 
         var session = name + "=" + escape( value );
         session += "; expires=" + expires.toGMTString();
         session += "; path=" + escape( path );
         session += "; domain=" + domain;
         session += secure;
         document.cookie = session;
         } catch( e ) { 
      } 
   } )( this.name, this.value, this.willExpire, this.path, this.domain, this.secure );
   }; Session.prototype.destroySession = function( name ) {
   this.name = "";
   document.cookie = name + "=" + ";path=" + this.path + ";domain=" + this.domain + ";expires=Thu, 01-Jan-1970 00:00:00 GMT"; 
   };

Thanks for the information so far. Here is the code from my other toggle script:

function toggle(showHideDiv, switchTextDiv) {
	var ele = document.getElementById(showHideDiv);
	var text = document.getElementById(switchTextDiv);
	if(ele.style.display == "none") {
    		ele.style.display = "block";
		text.innerHTML = "-";
  	}
	else {
		ele.style.display = "none";
		text.innerHTML = "+";
	}
}
function toggle2(contentDiv, controlDiv) {
        if (contentDiv.constructor == Array) {
                for(i=0; i < contentDiv.length; i++) {
                     toggle(contentDiv[i], controlDiv);
                }
        }
        else {
               toggle(contentDiv, controlDiv);
        }
}

It is basically the same but uses an array. I like your idea with separating the cookie script, I am just not sure how to make it work or reference it properly. What you have done is just created a session, then the cookie accesses the session?

Hi Tekkno,

here's a complete document sample.

Code for the cookie.js:
simplified version-

var session = { };
session.cookies = {
date : new Date(),
create : ( function( name, value, expires, path, domain, secure ) {
var name = name || "";
var value = value || "";
var path = path || "/";
var domain = domain || "";
var secure = secure || "";
var expires = (( expires ) ? ( expires * ( 1000 * 60 * 60 * 24 )) : ( 31 * 1000 * 60 * 60 * 24 ));

var willExpire = new Date( this.date.getTime() + expires );
var param = name + "=" + escape( value );
param += "; expires=" + willExpire.toGMTString();
param += "; path=" + escape( path );
param += "; domain=" + domain + ";";
param += secure;
   document.cookie = param;
   return;
} ),
retrieve : ( function( name ) { 
var extract;
var val;
var name = name || "";
   if ( name ) {
      try { 
      val = document.cookie.match("(^|;) ?" + name + "=([^;]*)(;|$)");
            extract = ( RegExp.$2 );
      } catch( d ) { 
      val = document.cookie.indexOf( String( name + "=" ));
         if ( val !== -1 ) {
         val += ((( val ) + name.length ) + 1 );
         var colon = document.cookie.indexOf( ";", val );
            (( colon !== -1 ) ? colon = document.cookie.length : colon = "" );
            extract = document.cookie.substr( val, colon );
            } else { 
            extract = 0;
            } 
         }
      } return (( extract ) ? unescape( extract ) : "" );
} ),
clear : ( function( name ) {
   var name = name || "";
   document.cookie = name + "=" + ";path=" + this.path + ";domain=" + this.domain + ";expires=Thu, 01-Jan-1970 00:00:00 GMT"; 
   } ) }

main page:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/css" href="#css_level21" media="screen"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<title>http://www.daniweb.com :: DHTML  JavaScript / AJAX</title>
<style id="css21" type="text/css">
/* <![CDATA[ */

/* ]]> */
</style>
<script type="text/javascript" src="cookie.js"></script>
<script type="text/javascript">
// <![CDATA[

var toggle = ( function( showHide, switchTextDiv ) {
   var ele = new Array();
   for( var i = 0; arguments[ i ]; i++ ) {
      if( typeof( ele[ i ] ) === "object" )
         ele[ i ] = ele[ i ];
      else
         ele[ i ] = (( ele[ i ] = document.getElementById( arguments[ i ] )) ? ele[ i ] : document.all[arguments[ i ]] );
   } var mode = { none : "<b>+</b>", block : "<b>-</b>" }[ ( ele[ 0 ].style.display = (( ele[ 0 ].style.display === "none" ) ? "block" : "none" )) ];
   session.cookies.create( ele[ 0 ].id, ele[ 0 ].style.display ); 
   ele[ 1 ].innerHTML = mode;
   session.cookies.create( ele[ 1 ].id, ele[ 1 ].innerHTML );
} );

/* Just keep this function as is-

your toggle() function will automatically saves new  session, for all the arguments that you will passed into its parameter, using your toggle2() function.

var toggle2 = ( function( contentDiv, controlDiv ) {
// your statement
} ); */

window.onload = ( function( state ) {
var state = state;
   return function() {
var count = 0;
var element = (( element = document.getElementsByTagName( "*" )) ? element : document.all );
      for( var x = 0; element[ x ]; x++ ) {
         if( element[ x ].id.indexOf( "nav" ) !== -1 ) {
         element[ x ].style.display = state.retrieve( element[ x ].id );

         }
      } // a bit tricky if you will just perform a single for loop statement.
 
      for( var y = 0; element[ y ]; y++ ) {
         if( element[ y ].id.indexOf( "control" ) !== -1 ) {
         element[ y ].innerHTML = state.retrieve( element[ y ].id );
         } 
      }
   }
} )( session.cookies );
// ]]>
</script>
</head>
<body id="xhtml11">
<div id="catOne">
<span id="controlOne" onclick="toggle( 'nav1', this );"><b>-</b></span>

<div id="nav1" class="show"><h3>Navigation 01</h3></div>
</div> <!-- #cat1 -->

<div id="catTwo">
<span id="controlTwo" onclick="toggle( 'nav2', this );"><b>-</b></span>

<div id="nav2" class="show"><h3>Navigation 02</h3></div>
</div> <!-- #cat2 -->

<div id="catThree">
<span id="controlThree" onclick="toggle( 'nav3', this );"><b>-</b></span>

<div id="nav3" class="show"><h3>Navigation 03</h3></div>
</div> <!-- #cat3 -->
</body>
</html>

-essential

Well, it doesn't look like that is working. The div's do not collapse with the script. However, this is much more complicated than I thought it was going to be. And way more code than I can understand. I appreciate your help essential but I don't expect you to write all this code for me. I'll just have to read up and try to get a better grasp on how javascript works. I've marked it as solved since you got the first script working. Thanks a lot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.