So, You Want To Set A Cookie, Huh?

This tutorial was really a long time coming. People have wanted it for a while, but I've been somewhat reluctant to write it for a couple of reasons.

First, I knew that as soon as I posted something like this I would see people setting cookies all over the place. Cookies are very bad in some people's eyes. You can read more about that in my original cookie reference piece. But furthermore... these things are hard!

Setting a cookie using JavaScript, which this tutorial does, can be a real pain in the neck. But now my neck feels fine and I've written basic cookie-place and cookie-retrieve scripts so we can move forward.

Why Set Cookies?

There are two main reasons that I can think of. The first is to "remember" information.
Someone comes to your page and offers you his or her name. Next time, you greet them by that name. Clever, and a nice touch. But again, many people are wary of cookies and won't feel comfortable accepting a cookie just so you can say "hi" at some later date.

The second reason, and the one I feel is most important, is moving information across pages.
Someone chooses something on one page, and when they click to go to the next page, what they chose before is now posted there for them. It's the whole basis for a shopping cart program.

My Cookie Script In Action

First off, this script is one I put together by heavily borrowing from the cookie script submitted by Giedrius. (That's all...just "Giedrius")

Any time you set a cookie, you need to gather some information. Usually it's done in the format I'm showing here. Someone enters something into a text box, a button is clicked, and the cookie is written that contains the information provided by the reader.

Once the cookie is written, you can call upon it again and again. Try this:

I should tell you up front, at the moment, the script will not post multiple words in the text box. It's easily fixed, but I'm trying to keep things pretty simple here, so just enter one word.

Setting the Cookie

Yes, it's not that stunning as is, but it gets the point across. If I had you enter your first name, then I could have welcomed you again and again each time you arrived. If this was an order form, the next page would have the number you ordered already posted to the page. Get the picture?

Let's start with the setting of the cookie. It's actually a little easier than the retrieval.

The form creates a text box and a button to fire up the function putCookie(). See that? The NAME of the form itself is "cf" and the NAME of the text box is "cfd". Now, when we want to grab what is written in the text box, we create the hierarchy statement: document.cf.cfd.value.

With me? Good. Moving to the script, we'll take it from top to bottom:

<SCRIPT LANGUAGE="JavaScript">

This starts any JavaScript.

cookie_name = "dataCookie";
var YouEntered;

The first line names the cookie. A variable "cookie_name" is created and the name I will call this cookie, "dataCookie", is assigned.
The second line simply sets a variable named "YouEntered". We'll assign a value to it later.

function putCookie() {

Here's the function name that is called for in the form button. Remember that?

Now to the meat of the script. The first thing we do is check to see if there even is a cookie. The line if(document.cookie != document.cookie) asks if the current cookie is not equal to the data entered by the user.

Writing that question actually saves a step. By asking if something is not equal to something else, I also ask if that something even exists. You see, if it doesn't exist, then it cannot be equal. Get it? I'm basically assuring that the cookie is rewritten each time the function is run.

This is an If/Else conditional statement, so here are the items:

If the cookie and the data do not equal, then set the cookie with the "cookie_name" "dataCookie".

If they do not equal, then index is equal to negative one (-1).

Why (-1)? Because JavaScript counts everything starting at zero, so to say to JavaScript that there is actually zero, you need to go one below zero... that's minus one.

Another If statement writes to the cookie. Now the variable name "YouEntered" is assigned the value entered into the text box using the "document.cf.cfd.value" hierarchy statement.

Finally, the document.cookie is written with the name, what the user entered, and a time for it to expire. I have the expire in this script set pretty far into the future. You can set yours to whatever you want, just follow the format shown in the script.

The final curly bracket and /SCRIPT round out the script. The cookie is set. Now we have to go get it.

What's It Look Like?

I have the pieces all on separate lines. In the cookie itself this was all on one line.
See the parts? There's the name of the cookie, the word I entered, where the cookie was set (from my hard drive), and then a really long number. That's the number of milliseconds until the expire date.

Retrieve the Cookie

Okay, we're set. A cookie has been written, but it's not much good to us unless we can go get it.

I'll show you this in two parts, the JavaScript code that grabs the cookie information and then the HTML/JavaScript that posts it to the page. The following is the code that appeared on the page you went to after setting the cookie.

After hitting the last script, this one should fall together pretty easily. We'll start after the &LT;SCRIPT LANGUAGE="javascript"&GT; tag.

cookie_name = "dataCookie";
var YouWrote;

This script assumes a cookie has been set. In fact, it assumes many cookies have been set so the name of the cookie is immediately noted. We are looking for the data found in a cookie named "dataCookie". A variable "YouWrote" is also created. Later it will be assigned the value from the cookie. You'll then use "YouWrote" to represent the cookie's data.

function getName() {

The function is called getName().

if(document.cookie)
{
index = document.cookie.indexOf(cookie_name);

If a no cookie exists, then the index should be the one in dataCookie. But we know one exists.

As you saw above, it is the second piece of information in the cookie we're interested in. This code grabs a substring of the cookie represented by the second item. It then assigns that value to YouWrote and returns it to the script.

YouWrote=getName();

Every function must have a trigger to make it work. Here's the one that fires up "getName()" assigning its output to "YouWrote".

if (YouWrote == "dataCookie")
{YouWrote = "Nothing_Entered"}

This little blip of code is used if nothing is entered. When you submit nothing (no data) to the cookie, the name of the cookie is returned by the function. This says that if the "YouWrote" equals dataCookie, the name of the cookie, then the value assigned should be "Nothing_Entered". It just looks a little cleaner.

Putting the Cookie on the Page

It's a fairly simply process from this point on. You have a variable, YouWrote, that represents the value of the cookie. Just use that variable name to post the data to the page through document.write commands. This is how I did it on the secondary page in this tutorial:

The first simply prints it to the page, the second puts it into a text box. Note the code that creates the text box requires the &LT;FORM&GT; tags, too.

More Than One Cookie

The code you got here is pretty much copy-and-paste easy to install. But let's say you want to set multiple cookies. You'll need to remember that the two scripts you got here are links. The first sets the cookie, the second retrieves it. So any changes you make to one script, you'll need to make to the other.

First and foremost, you'll need to set a new cookie name, then new variable names to represent the data. Please note that those variable names appear throughout the script, so make sure you get them all. I do it with my text editor's "Replace All" function.

If you grab the cookie the way I did, using a form, then you'll need to make sure the form element's NAMEs are correctly represented in the script's hierarchy statements.

Don't sweat it. It's a little work, but you'll get it down soon enough. Just remember to keep a backup of the original working scripts. I wasted over an hour this time around by editing the original. That's what I get for writing a JavaScript book....