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)
saveCookie("favourite cookie","chocolate chip",360) // save for 1 year
readCookie(name)
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)
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 |