Standard HTML & JavaScript for Handling a Cookie

Mindwatering Incorporated

Author: Tripp W Black

Created: 11/05/1999 at 06:21 PM

 

Category:
Notes Developer Tips
E-Commerce, ViewTemplates

<html>

<head><title>cookie example</title>
<script language="JavaScript">
<!-- hide

// Heinle's function for retrieving a cookie.
function getCookie(name){
var cname = name + "=";
var dc = document.cookie;
if (dc.length > 0) {
begin = dc.indexOf(cname);
if (begin != -1) {
begin += cname.length;
end = dc.indexOf(";", begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin, end));
}
}
return null;
}


// An adaptation of Dorcht's function for setting a cookie.
function setCookie(name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
((secure == null) ? "" : "; secure");
}

// An adaptation of Dorcht's function for deleting a cookie.
function delCookie (name,path,domain) {
if (getCookie(name)) {
document.cookie = name + "=" +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}

//set expiration date 7 days ahead
var expiration = new Date();
expiration.setTime(expiration.getTime() + 604800000);


var x = 3;
var temp = getCookie("visits");

if (temp != "done") {
if (temp == null) {
temp = 1;
setCookie("visits", temp, expiration);
} else {
if (temp < x-1) {
temp++;
} else {
temp = "done";
alert("you've visited " + x + " times and win a prize!");
}
setCookie("visits", temp);
}
}

// done hiding -->
</script>
</head>

<body bgcolor="#ffffff">

<script language="JavaScript">
<!--

document.write("Visit this page a total of " + x + " times (reload " + eval(x-1) + " times) to receive the message.");

// -->
</script>

</body>
</html>

previous page