Cookie Functions

Cookies are a way to store a small piece of information in a visitors browser. Some people get paranoid about them because they feel the web authors are tracking them, but usually they are just used to gather simple information about their visitors. Information such as:

Using cookies are not specific to DHTML or JavaScript, almost any programming language for the web is capable to producing them such as Java, Perl, ASP, C++ etc. In server-side languages this is done by printing a line of text before the HTML content is shown. An advantage that JavaScript has is that it can give you a cookie at any time you are viewing a page, you don't have to go to another page in order to give a cookie.

In the DynAPI there is a cookies.js file which you can use to easily save, read, and delete cookies. Include the file and you'll have 3 functions:

saveCookie(name,value,days)

The cookie's name is a variable of your choice, it will be how you'll reference the cookie value. The value is the piece of information that you want to store. It can be a String or Number but will actually be stored as a String in either case. The days is how long until the cookie will be stored before expiring. If you only want to store the cookie for the current browser session, then 0 should be the number of days.
saveCookie("favourite cookie","chocolate chip",360)  // save for 1 year

readCookie(name)

This will return the value of the cookie as a String. If the cookie does not exist, it will return null. You'd usually read a cookie like this:
var favcookie = readCookie('favourite cookie')

if (mycookie==null) {  // cookie does not exist
	
}
else {  // cookie exists
	
}

If the value is a number you'll have to use parseInt() to make it an integer.

deleteCookie(name)

This will remove the cookie. Actually all it does is re-save the cookie with a days value of -1, which means the cookie expired yesterday.
deleteCookie('favourite cookie')

The example below will count the number of times that you've read the page. When you reload the number will go up. I read the cookie value, and write a sentence depending on the value of the cookie, then I increment the counter using parseInt() to make sure it's a number, and then re-save the cookie:

var count = readCookie('pagecount')  // read the 'pagecount' cookie

if (count==null) {  // if no cookie
	document.write("<li>never visiting this page before")
	count = 0  // set counter to 0
}
else {  // if cookie exists
	document.write("<li>visted this page "+count+" times before")
}

count = parseInt(count)+1  // increment the counter

saveCookie('pagecount',count,360) // save 'pagecount' cookie for 360 days

Example cookies1.html [source]

Home Next Lesson: Creating Reusable Widgets
copyright 1998 Dan Steinman