// setCookie function
// Analysis
function setCookie(name, value)
{
var expires=new Date();
expires.setYear(expires.getYear() + 1);

var cookieString = name + "=" + escape(value) + "; expires=";
cookieString += expires.toGMTString();

document.cookie = cookieString;
}

This is the setCookie function, which is responsible for updating and creating cookies. It accepts two arguments -- name and value.

The code begins by creating a new date object. When a date object is created without any arguments, it is instantiated with the current date. Because we want our cookie to expire in a year's time, we have to use the setYear() method to increase the year by 1. However, before we can increase the year, we have to use the getYear() method to extract the current year.

The next section of code creates a temporary string called cookieString, and begins writing the cookie information. The name argument is assigned to the string, followed by an equals sign and the value. Notice that the escape() method is used on the value property so that our values can contain spaces and other illegal characters if necessary.

Next, a semicolon is appended to the string, followed by a space and the string 'expires='. Finally, the expires date object is converted to GMT time using the toGMTString method, and the value is added to the string.

The last line of code actually writes the cookie by assigning the cookieString variable to the document.cookie property.

Close Window