Cookies: Variables that Last

Consider the following script:

name = prompt("What is your name?");
document.write("Hello " + name);

This will run every time someone visits the page - which could get annoying. The problem is that the variable name doesn't last. The web-browser forgets it when the user leaves the page.

Cookies let us create variables that last. A cookie is stored on the user's browser, and is available next time they visit the page.

Cookie Functions

Cookies are quite simple. Unfortunately though, the code for using cookies is quite advanced and idiosyncratic. Here we define 3 functions to make using cookies easier. Don't worry about how they work. You can just copy and paste them into your web page.

// Place the code below in a JavaScript block

Create a cookie
   name - name of the cookie
   value - value of the cookie
These cookies will ask to stay alive for a year.
function setCookie(name, value) {
   var largeExpDate = new Date ();
   largeExpDate.setTime(largeExpDate.getTime() + (365 * 24 * 3600 * 1000)); // Last for a year - note that the browser may not respect this.
   // Create the cookie string
   var curCookie = name + "=" + escape(value) + "; expires="+largeExpDate.toGMTString()+";";
   // Add it to the document
   document.cookie = curCookie; // Note that this *doesn't* re-assign document.cookie (which would delete all existing cookies).
   // It magically appends the new cookie to the list.

  name - name of the desired cookie
  Return a string containing the value of specified cookie, or null if cookie does not exist
function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1) end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));

// Convert a cookie into a number (otherwise it will be a string)
function getNumberCookie(name) {
   return parseInt( getCookie(name) );

This creates the following functions:

setCookie("CookieName", value);
This creates a cookie (or sets a new value for an existing cookie).

value = getCookie("CookieName");
If the cookie doesn't exist then this will return false - so you can also use it to test whether a cookie has been created.

value = getNumberCookie("CookieName");

The example below counts how many times you visit this page.

visits = getNumberCookie("visits");
if (!visits) {
    // Set visits to a starting value if it doesn't exist
    visits = 0;
document.write("You have been here " + visits + " times.");
setCookie("visits", visits);