Skip to content

Instantly share code, notes, and snippets.

@cesarmiquel
Created December 21, 2011 17:40
Show Gist options
  • Save cesarmiquel/1506921 to your computer and use it in GitHub Desktop.
Save cesarmiquel/1506921 to your computer and use it in GitHub Desktop.
Cookie managing functions
// helpers to manipulate cookies. see: http://www.quirksmode.org/js/cookies.html
/**
* Create a cookie for site
*
* @param name Name for cookie
* @param value Value for cookie
* @param minutes Number of minutes this cookie will be valid for.
*/
function createCookie(name, value, minutes) {
if (minutes) {
var date = new Date();
date.setTime( date.getTime() + (minutes * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else {
var expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
/**
* Retrieve a cookie
*
* @param name Name of cookie
* @returns The value stored in the cookie null otherwiste.
*/
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);
}
// workaround for a in chrome (old version)
if ( i == ca.length ) {
return null;
}
if ( c.indexOf( nameEQ ) != -1 ) {
return c.substring( nameEQ.length, c.length );
}
}
return null;
}
/**
* Remove cookie
*
* @param name Cookie name.
*/
function eraseCookie(name) {
createCookie(name,"",-1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment