Cookies in JavaScript

Permanent Link: Cookies in JavaScript 29. Juli 2009 RSS Feed for comments on RSS-Feed für Kommentare zu: Cookies in JavaScript comments feed

Using in Cookies is rather complicated. All the cookies are in the string document.cookie. Here's a little static class I wrote a while ago to handle saving, reading and removing Cookies in JavaScript

/**
* Static Class for Cookie functions
*/
function Cookie()
{
}

/**
* Save new Cookie
*
* @param string name
* @param string value
* @param number days
*/
Cookie.save = function(name, value, days)
{
if (typeof days != 'undefined') {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
var expires = "; expires=" + date.toGMTString();
} else {
var expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}

/**
* Read Cookie value
*
* @param string name
*/
Cookie.get = function(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);
}
if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length,c.length);
}
}
return null;
}

/**
* Delete Cookie
*
* @param string name
*/
Cookie.remove = function(name) {
Cookie.save(name,"",-1);
}

0 comments

No Comments yet.

Write a comment

(will not be published)