Free Java script functions for setting, reading and removing cookies
Posted On at by milanCreate Cookie
function createCookie(name, value, hours)
{
if (hours) {
var date = new Date();
date.setTime(date.getTime()+(hours*60*60));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
Above function can be used to set cookie. It takes name, value of cookie and hours after which cookie will expire. You can modify function to give time in days or minutes. Just ultimate goal is to convert the time given into seconds and provide it to origional cookie setting instruction.
Read Cookie
If you provide the name of already set cookie to following function it will read the cookie value for you.
function readCookie(name)
{
var ca = document.cookie.split(';');
var nameEQ = name + "=";
for(var i=0; i <>
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
delete Cookie
This simple function deletes cookie of given name using above create cookie function.
function deleteCookie(name)
{
createCookie(name, "", -1);
}