| | |
Setting cookie for toggle function
Please support our JavaScript / DHTML / AJAX advertiser: PostgreSQL or MySQL? Compare and contrast the two most popular open source databases
Thread Solved |
•
•
Join Date: Apr 2009
Posts: 59
Reputation:
Solved Threads: 1
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:
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.
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
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.
•
•
Join Date: Aug 2007
Posts: 165
Reputation:
Solved Threads: 18
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).
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:
hope it helps...
but if you still want to claim things with cookies.
Then here is my demo:
javascript Syntax (Toggle Plain Text)
<?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...
Last edited by essential; Aug 7th, 2009 at 12:25 am.
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
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
Dev.Opera — FOLLOW THE STANDARDS, BREAK THE RULES...
•
•
Join Date: Apr 2009
Posts: 59
Reputation:
Solved Threads: 1
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.
Last edited by Tekkno; Aug 7th, 2009 at 1:15 am.
Claim this as a normal part of your .js files'
then reference it via
cookie.js
then reference it via
<script type="text/javascript" src="./cookie.js"></script> tag.cookie.js
javascript Syntax (Toggle Plain Text)
/* ~ 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"; };
Last edited by essential; Aug 7th, 2009 at 4:57 am.
•
•
Join Date: Apr 2009
Posts: 59
Reputation:
Solved Threads: 1
Thanks for the information so far. Here is the code from my other toggle script:
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?
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
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); } }
![]() |
Similar Threads
- Passing data from forms from one page to another (JavaScript / DHTML / AJAX)
- setcookie not setting cookie... (PHP)
- persistant cookie for select function (JavaScript / DHTML / AJAX)
- Quick Help for Cookie script? (JavaScript / DHTML / AJAX)
- Setting up a cookie and saving the result in mySQL database (PHP)
- Javascript generated drop down menu (JavaScript / DHTML / AJAX)
Other Threads in the JavaScript / DHTML / AJAX Forum
- Previous Thread: A little problem I aam haaving wih a drag and drop
- Next Thread: How do you return a multi-demensional array using Prototype Hash
| Thread Tools | Search this Thread |
acid2 ajax ajaxexample ajaxjspservlets array browser bug captchaformproblem cart checkbox child class close codes createrange() css cursor date debugger decimal dependent design disablefirebug dom dropdown editor element embed engine enter error events explorer ext file firefox focus form forms frameworks getselection google gxt hiddenvalue highlightedword hint html ie7 ie8 iframe images index internet java javascript javascripthelp2020 jquery jsf jsfile jsp jump libcurl listbox maps masterpage math media menu mp4 object onmouseoutdivproblem onmouseover onreadystatechange parent paypal pdf php position post problem programming progressbar prototype redirect runtime safari scale scriptlets scroll search security shopping size software toggle unicode w3c web wysiwyg \n





