02/10/2014

JavaScript Cookies II

function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() +
(exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
Example explained:
The parameters of the function above are the name of the cookie (cname), the value of the cookie (cvalue), and the number of days until the cookie should expire (exdays).
The function sets a cookie by adding together the cookiename, the cookie value, and the expires string.
A Function to Get a Cookie
Then, we create a function that returns the value of a specified cookie:
function
getCookie(cname) {
var name = cname + "="; var ca =
document.cookie.split(';'); for(var i=0; i var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) return
c.substring(name.length,c.length);
}
return "";
}
Function explained:
Take the cookie name as parameter (cname). Create a variable (name) with the text to search for (cname + "="). Split document.cookie on semicolons into an array called ca (ca = document.cookie.split(';')). Loop through the ca array (i=0;i(c.indexOf(name) == 0), return the value of the cookie
(c.substring(name.length,c.length)
var name = cname + "="; var ca =
document.cookie.split(';'); for(var i=0; i var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) return
c.substring(name.length,c.length);
}
return "";
}

Function explained:
Take the cookie name as parameter (cname). Create a variable (name) with the text to search for (cname + "="). Split document.cookie on semicolons into an array called ca (ca = document.cookie.split(';')). Loop through the ca array (i=0;i
Practice makes a man perfect