Skip to content

Instantly share code, notes, and snippets.

@computercarguy
Created June 26, 2012 17:13
Show Gist options
  • Save computercarguy/2997191 to your computer and use it in GitHub Desktop.
Save computercarguy/2997191 to your computer and use it in GitHub Desktop.
JavaScript Cookies
// I've had this file for a long time and it seemed like a good feature to add here
function CreateCookie(Name, Value, Days) {
// creates a cookie for web pages
// creates the cookie Name, sets the Value, and then makes it last however long the Days are
if (Days) {
NewDate = new Date();
NewDate.setTime(NewDate.getTime() + (Days * 24 * 60 * 60 * 1000));
Expires = "; expires=" + NewDate.toGMTString();
} else {
Expires = "";
}
document.cookie = Name + "=" + Value + Expires + "; path=/";
}
function ReadCookie(Name) {
// attempts to read a previously created cookie and returns the data, or returns "null" if there isn't a cookie
Name = Name + "=";
CookieArr = document.cookie.split(';');
for (i = 0; i < CookieArr.length; i++) {
while (CookieArr[i].charAt(0) == ' ') {
CookieArr[i] = CookieArr[i].substring(1, CookieArr[i].length);
}
if (CookieArr[i].indexOf(Name) == 0) {
return CookieArr[i].substring(Name.length, CookieArr[i].length);
}
}
return null;
}
function EraseCookie(Name) {
// deletes the cookie Name by setting the time to be kept to a past time
CreateCookie(Name, "", -1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment