Menu


AJAX Enabled


Andrew Pallant's Weekly Code Snippet


Manage Cookies using JavaScript

This week's code sample is JavaScript based. I found this while researching JavaScript cookie routines.  I personally cannot take credit for creating this routine, but I thought it would be good to share this example with other developers.

Credit given: http://www.the-cool-place.co.uk/javascript/cutandpaste/cutandpaste15.html

For more great scripts: http://www.the-cool-place.co.uk/javascript/

Important Note: Works with IE and FireFox

Input your name and press the button to see the results of the cookie.
Name:

function getexpirydate( nodays)

     var UTCstring; 
     Today = new Date(); 
     nomilli=Date.parse(Today); 
     Today.setTime(nomilli+nodays*24*60*60*1000); 
     UTCstring = Today.toUTCString(); 
     return UTCstring;
}

function getcookie(cookiename)

     var cookiestring=""+document.cookie; 
     var index1=cookiestring.indexOf(cookiename); 
     if (index1==-1 || cookiename=="") return "";
 
     var index2=cookiestring.indexOf(';',index1); 
     if (index2==-1) index2=cookiestring.length; 

     return unescape(cookiestring.substring(index1+cookiename.length+1,index2));
}

function setcookie(name,value,duration)
{
    cookiestring=name+"="+escape(value)+";
     EXPIRES="+getexpirydate(duration);
     document.cookie=cookiestring;
     window.location.reload();
}