Two Hoots Banner



Cookie Javascript
A cookie is a small amount of data stored by your browser and associated with a web page or site. This allows information to be retrieved about your previous visit for example, allowing your web site to display a personalised welcome message. The following code provides a basic introduction into cookies.
The setCookie() routine saves the cookie with the value entered in the text box. The getCookie() routine retrieves the saved value and displays it in an alert box. Finally the deleteCookie code deletes the created cookie by setting the expiry date to now.

function setCookie(){
 // prompt for cookie value
 var myvalue=prompt("Enter cookie value", "cookie value here");
 var mycookie="myvalue="+escape(myvalue);
 var myexpires=new Date();
 myexpires.setTime(myexpires.getTime()+365*24*60*60*1000);
 // expire after one year
 mycookie=mycookie+";myexpires="+myexpires.toGMTString();
 document.cookie=mycookie;
}
		 
function getCookie(myname){
 // pass name of cookie to be retrieved
 // read the entire cookie
 var mycookie=document.cookie;
 var myname=myname+"=";
 var mystart=mycookie.indexOf(myname);
 // found it - if null return empty
 if(mystart<0){return null;}
   var myend=document.cookie.indexOf(";",mystart);
 if(myend<0){myend=mycookie.length;}
   // return the value requested
 return unescape(mycookie.substring(mystart+myname.length,myend));
 }
		 
function deleteCookie(myname){
 if (getCookie(myname)){
  // set expire date to immediately so that the browser deletes it for us
  document.cookie=myname+"="+";expires=0";
 }
}
Use the following buttons to test the above code by entering a value for a cookie and then click the 'Set Cookie' button. Use the 'Get Cookie' button to display the value of the cookie.

set cookie
get cookie
delete cookie