Create, update, and delete JavaScript Cookie
What is Cookie?
Cookies are data, stored in small text files, on your computer.
Cookies are saved in name-value pairs like:
username=Jahidul Islam
Create a Cookie with JavaScript
Make a simple cookie just assigning name-value pair
document.cookie="username=Jahidul Islam";
Making a cookie with the expiry date
document.cookie="username=Jahidul Islam; expires=Thu, 18 Dec 2060 12:00:00 GMT";
Making cookie with expiry date and the path where cookie belongs to. By default, the cookie belongs to the current
page.
document.cookie="username=Jahidul Islam; expires=Thu, 18 Dec 2013 12:00:00 GMT; path=/";
Read a Cookie with JavaScript
var x = document.cookie;
document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;
Change a Cookie with JavaScript
you can change a cookie the same way as you create it:
document.cookie="username=Jahidul Islam Jahid; expires=Thu, 18 Dec 2013 12:00:00 GMT; path=/";
Delete a Cookie with JavaScript
Deleting a cookie is very simple. Just set the expires parameter to a passed date:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
Example
<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays){
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname){
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
function checkCookie(){
var user=getCookie("username");
if (user!="")
{
alert("Welcome again " + user);
}
else
{
user = prompt("Please enter your name:","");
if (user!="" && user!=null)
{
setCookie("username",user,30);
}
}
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>
Comments 0