Demo 1:
http://mwebng.net/demos/cookies/change.htm - storing personal info
Demo 2:
http://mwebng.net/demos/cookies/jc2.htm - javascript counter
You can download those demos on
http://mwebng.net/?net=dlI will not explain those source codes - those are complete samples - but rather i want to give a short training on the basics of cookies.
At this point i am tempted to create a cookie class for easy learning, then i will now break down the class
cookie.class.js
function jcookies() {}
jcookies.prototype.online=function() {return location.href.indexOf("http")==-1 ? false : true;}
jcookies.prototype.set=function (cname,cvalue) {
if(this.online()) {document.cookie = cname + "=" + escape(cvalue) + "; expires=Mon, 31 Dec 2099 23:59:59 UTC;path=/;";}
else {document.cookie = cname + "=" + escape(cvalue) + "; expires=Mon, 31 Dec 2099 23:59:59 UTC;";}
}
jcookies.prototype.erase=function(cname) {
if(this.online()) {document.cookie = cname + "=" + "" + "; expires=Mon, 31 Dec 1899 23:59:59 UTC;path=/;";}
else {document.cookie = cname + "=" + "" + "; expires=Mon, 31 Dec 1899 23:59:59 UTC;";}
}
jcookies.prototype.get=function(sName) { var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++) {
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}
return "";
}
The class contains 3 methods/functions:
set - to create a cookie
get - to retrieve a cookie
erase- to clear out a cookie
I am going to implement that class now
cookie.test.html
<title>My Cookie Test</title>
<script src="cookie.class.js"></script>
<script>
var food=new jcookies();
function savex() {
food.set("meal",cook.value);
alert("Swallowed "+cook.value);
}
function loadx() {
cook.value=food.get("meal");
}
function erasex() {
cook.value="";
food.erase("meal");
alert("Vomited meal");
}
</script>
<input type="text" id="cook">
<input type="button" value="Save" onclick="savex()">
<input type="button" value="Load" onclick="loadx()">
<input type="button" value="Vomit" onclick="erasex()">
I will leave it for you to compile the 2 - demo will be
http://mwebng.net/demos/cookies/cookie.test.htmlAnd for this demo, all you need do is launch it, type in a value, click on save.
You can close the browser, then reopen the page in the same browser on the same system, then click on the load button, u should have your contents back.
Next lesson: we are going to break the code code into bits and pieces.