JavaScript : Smart Sites and Cute Cookies
Contents ]
Dr Benton

Function for Writing a Cookie

The following function adds a cookie in which we will write a name, a value and an expiry date:

nomCookie = "MyCookie";
nombreVisites = 0;

function ecritCookie(nom, valeur, expire)
{
  // We ask the browser to write the cookie
  document.cookie = nom + "=" + escape(valeur + "!" + nombreVisites.toString()+"!") + ((expire == null) ? "" : ("; expires=" + expire.toGMTString()))
  nombreVisites++;
}

The function escape() converts the variable valeur into characters which can be written in the cookie. As for nombreVisites.toString(), this converts the number of visits into a character string, the only acceptable data type in a cookie.

What's in a function? The first two lines are not part of the function, and have to be placed right behind the script opening tag (<SCRIPT>). They define the variables nomCookie and nombreVisites which will be used by our JavaScript functions.

The right name. MyCookie is the generic name which all our cookies will start with. So choose a descriptive name which might not be used by another site.



  1   2   3   4   5   6   7