Richard's JavaScript Tutorials

Updated 07/18/14

Home
Animation
precachedImages
digitalClock
Object Tag (Audio)
Cookies.htm
Math_Object
Using CSS
The Style Object
Client_Info
customObject
functions
UsingArrays
comments
concatenation
documentwrite
ifelse
Loops
forms
Strings
variables

 

Using cookies with JavaScript

In this section I will demonstrate the use of Cookies. First let's take a look at a very simple cookie. This is a cookie that will display the name and Expiration date in an alert box when you click the display cookie button.

// Here the cookie is being created just a simple cookie

document.cookie = "username=" + escape("New_Cookie")s=07/17/+ "; 'expire2007";

// Here the cookie is assigned to a variable so it will display properly
var myvar = "username=" + escape("New_Cookie")+ " expires=07/17/2007";

 


Now we will create a cookie counter. First a cookie will be created and then it will keep track 
of  how many times that you visited this page and display the number on the page. This
script I found to be a bit harder to do and honestly I had a little help in creating it.
And now here is the code for the script above:
<html><head>
<title>Cookie Counter</title>
<script type="text/javascript">
<!--
function getCookie(name) 
{
var start = document.cookie.indexOf(name+"=");
var len = start+name.length+1;
if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
if (start == -1) return null;
var end = document.cookie.indexOf(";",len);
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(len,end));
}
function setCookie(name,value,expires,path,domain,secure) 
{
document.cookie = name + "=" +escape(value) +
((expires) ? ";expires=" + expires.toGMTString() : "") +
((path) ? ";path=" + path : "") + 
((domain) ? ";domain=" + domain : "") +
((secure) ? ";secure" : "");
alertDisplay = document.cookie;
}
var blah = getCookie("cookieTest");
var expireDate = new Date("07/1/2007");
if (blah != null) 
{
blah = parseInt(blah, 10) + 1;
setCookie("cookieTest", blah, expireDate);
}
else 
{
blah = 1;
setCookie("cookieTest", blah, expireDate);
}
//--></script>

</head><body>
<script type="text/javascript">
<!--
document.write("You have been to this site " + blah + " time(s)");
//--></script></body></html>

Home | Animation | precachedImages | digitalClock | Object Tag (Audio) | Cookies.htm | Math_Object | Using CSS | The Style Object | Client_Info | customObject | functions | UsingArrays | comments | concatenation | documentwrite | ifelse | Loops | forms | Strings | variables

This site was last updated 07/18/14