You are on page 1of 7

10/11/2009 Learning JavaScript - Menus and Cooki…

Check this Freebie out!


I n t e rn e t A cce ss - Fre e Tria ls a n d S p e cia ls
NetZero, Juno, PeoplePC, EarthLink, AOL and more!

Menus and Cookies


(Lesson 13)

This is an intense lesson where you can learn how to design menus that utilize
JavaScript. You will then learn all about the famous Cookies that you have heard
so much about. Here, I have tried to cover these two subjects "step by step" so
that you can understand the workings of both.

Menus
You can use the Rollovers that we talked about in Lesson 12 to create some
cool menus if you want. That is what I did for the menu on the left side of each of
these pages.

Another way to create a menu utilizing JavaScript is to use a d ro p d o wn lis t as


shown in the simple demo below. I included a few of our lessons in the menu for
this demo. Try it if you want, but remember you will need to use the back button
on your browser to return to this page. If you decide to use this type of menu, then
you will probably want to put a similar menu on all your pages.

Lesson 13

The JavaScript code for a menu such as the one above is really quite short but I
find it difficult to understand. So, I decided to take the lengthy approach to
explaining the code here. If you are interested in just the final code, then feel free
to go here to see it.

The d ro p d o wn lis t is one of the elements that is available in a Fo rm.


rm We
discussed the basics of the Form in Lesson 6. You may want to take a look at
that now to refresh your memory. I also strongly recommend that you visit our
Library and study the section on Forms at "Sizzling HTML Jalfrezi".

Here is the HTML code I used to create the drop down list for our demo:

<FORM NAME="demo">
<SELECT NAME="menu" onChange="loadPage()">
<OPTION VALUE="lesson11.htm">Lesson 11
<OPTION VALUE="lesson12.htm">Lesson 12
<OPTION SELECTED VALUE="lesson13.htm">Lesson 13
<OPTION VALUE="lesson14.htm">Lesson 14
</SELECT>
</FORM>

As shown in the above HTML code, the <SELECT> tag is used to create a drop
down list.

Nested between the <SELECT> and </SELECT> tags are <OPTION> tags.

Note that there is one <OPTION> tag for each menu entry. The V A LU E property
of the <OPTION> tag contains the URL of a page and the text following the tag

javascriptmall.com/learn/lesson13.htm 1/7
10/11/2009 Learning JavaScript - Menus and Cooki…
appears in the drop down menu list.

Note that our third <OPTION> tag in the list has S E LE CT E D in it. This identifies
the selection that will be the default when the page loads.

The onChange method of the <SELECT> tag calls a function that is used to load
the specified URL. Here is the code for that function.

function loadPage(){
var sel_idx = document.demo.menu.selectedIndex
var urlToLoad = document.demo.menu.options[sel_idx].value

location.href = urlToLoad
}

It is important to understand that the o p tio n o b je c t that is defined by the


<OPTION> tags is an Array. In the function above, the variable s e l_id x is set
equal to the value of the s e le c te d Ind e x.
x The s e le c te d Ind e x is the number of
the selected element of the array (remember that the number of the first element
in an Array is 0). The urlT o Lo a d variable is the value of the option element that
has been selected, which is the URL of the page we wish to load.

Click here if you would like to test our drop down list menu and see the values of
s e l_id x and urlT o Lo a d that result when you select each of the possible
options.

The last line of the function loads the page into the browser utilizing the lo c a tio n
o b je c t.
t

Final Drop Down List Code for our Menu


The code we did above will work just fine. However, most of the time you will see
the loadPage() function and Form code written as shown below:

function loadPage(fInfo){
location.href = fInfo.options[fInfo.selectedIndex].value
}

<FORM NAME="demo">
<SELECT NAME="menu" onChange="loadPage(this)">
<OPTION VALUE="lesson11.htm">Lesson 11
<OPTION VALUE="lesson12.htm">Lesson 12
<OPTION SELECTED VALUE="lesson13.htm">Lesson 13
<OPTION VALUE="lesson14.htm">Lesson 14
</SELECT>
</FORM>

The only change in the form is the lo a d P a g e () function now contains a


parameter and the parameter is the JavaScript keyword this . The this keyword
allows all of the information about the S ELE CT object to be passed to the
function. For instance, in the function, fInfo.selectedIndex is the same as
document.demo.menu.selectedIndex. Everything that we did in our

javascriptmall.com/learn/lesson13.htm 2/7
10/11/2009 Learning JavaScript - Menus and Cooki…
original version of the lo a d Pa g e () function is now written on one line. If you
study it close, I think you will see that both versions will have the same results.

Some Final Thoughts on our Discussion of Menus


The this keyword has always been confusing to me but I will try to explain its
meaning as best I understand it. The this keyword always refers to the object
where it is used. For instance, when you pass it as a parameter to a function, the
this keyword refers to the object that was used to call the function.

In our example menu, we passed the this keyword to a function from the
SE LE CT object. Therefore, in the function the variable fInfo refers to the
SE LE CT object or more specifically will be the same as using
document.demo.menu.

In our example menu, fInfo.selectedIndex is the same as


document.demo.menu.selectedIndex and fInfo.options[] is the
same as document.demo.menu.options[].

The lo c a tio n o b je c t is used to load a specific URL into your browser. Just
make location.href equal to the URL that you want to load. In our menu script
above I used a relative URL since the page was on my website. You can
specify the complete URL if you want. For instance, I could have used
location.href = "http://www.crays.com/learn/lesson11.htm"
to load my lesson 11 page. You will need to specify the complete URL for pages
that are not on your website.

The lo c a tio n o b je c t can be used to load pages into a different Frame if your
site is using Frames or into a different browser window. Visit our Library to learn
how to do this if you are interested.

By default the <SELECT> tag results in a drop down box like we demonstrated
above. Using the S IZE property, you can make the <SELECT> tag result in a
scrolling list. For example
<SELECT SIZE=3 NAME="menuDemo" onChange="loadPage(this)">
will result in a scrolling list of 3 elements.

Take a look at the first problem Assignment below to see a demonstration of a


website utilizing a drop down menu. You can find more Menu examples on my
JavaScript Corral Site.

Cookies
A Cookie is a small piece of data that is stored in memory or on your hard drive.
These cookies are used to give your web browser memory to be used from one
web page to the other or from one visit to the other.

Many people are leery of Cookies because of a fear that their privacy is being
invaded. In the case of JavaScript, all cookie data remains on the computer that
created it. You need a more sophisticated language if you want to send this data
back to the server.

If you look back at the Property Summary of the document Object in lesson 12,
you will see that a cookie is a string value. This string contains information in a
special format that we can read and write to the hard drive.

javascriptmall.com/learn/lesson13.htm 3/7
10/11/2009 Learning JavaScript - Menus and Cooki…
Cookies are stored in a file named cookies.txt if you are using Netscape
Navigator on a PC and in a file named MagicCookie on the Mac. Internet
Explorer saves each individual cookie as a file in a directory named Cookies. I
recommend that you make a second copy and use that if you want to look at a
cookie file in a editor since any changes will probably make the file useless.

Our First Cookie


We will be making a total of 3 cookies in this lesson. Two of them will be
temporary and the final one will persist on your hard drive for one day.

Let's take a look a simple cookie using the form below.

Set Cookie Get Cookie String

First, press the Ge t Co o k ie S tring button. An alert box is displayed with nothing
in it.

Enter something into the te xt b o x and press Se t Co o k ie . Now when you press
the Ge t Co o k ie S tring button, the alert box displays
no1=text you entered (no1 is the name that I gave the cookie).

Try typing some different information in the te xt b o x and pressing the S e t


Co o k ie button and then the Ge t Co o k ie String button.

Here is the syntax that you use to set this simple cookie.

document.cookie="nameofCookie=cookieData"

For our form, I named the cookie no1 and got the cookieData from our te xt
b o x in the form. Here is the code that I used. You will see how this all worked by
examining the onClick events for the two buttons.

<FORM name="frm1">
<INPUT type="text" length=20 name="txt1">
<P>
<INPUT type="button" value="Set Cookie" name="set1"
onClick='document.cookie="no1="+document.frm1.txt1.value'>
<INPUT type="button" value="Get Cookie String" name="get1"
onClick='alert(document.cookie)'>
</FORM>

Realize that most of the code shown above was used for this demo and does
not represent a practical way to set or display a cookie. The code that was used
to set the cookie was made bold so that it can easily be identified. The cookie
data was shown by displaying it in a simple alert box using the onClick event of
the second button.

A Second Cookie
Here is a form that will make a second cookie for us named no 2.
2

javascriptmall.com/learn/lesson13.htm 4/7
10/11/2009 Learning JavaScript - Menus and Cooki…

Set Cookie Get Cookie String

When you enter something into the te xt b o x,x press Se t Co o k ie and then press
Ge t Co o k ie String , the alert box displays a string that contains the name and
data for both cookies. Note that the two cookies are separated by a semicolon
(; ).

Here is the code that I used for our second form.

<FORM name="frm2">
<INPUT type="text" length=20 name="txt2">
<P>
<INPUT type="button" value="Set Cookie" name="set2"
onClick='document.cookie="no2="+document.frm2.txt2.value'>
<INPUT type="button" value="Get Cookie String" name="get2"
onClick='alert(document.cookie)'>
</FORM>

Our Third Cookie


All cookies we have done so far are temporary. When you close your browser
and reopen it, the cookie will no longer exist. In fact these cookies only remain in
memory and are never written to the hard drive.

If you want a cookie to be written to a person's hard drive so that it will be


available for future visits, then you need to set the expires attribute of the cookie.
Here is the syntax for setting a cookie that has an expiration date.

document.cookie="nameofCookie=cookieData; expires=time"

The time must be passed as a Greenwich Mean Time string.

Lets create a third cookie and save it this time.

Set Cookie Get Cookie String

Here are the functions that I used to make this third cookie.

function getCookieExpireDate(noDays){
var today = new Date()
var expr = new Date(today.getTime()+noDays*24*60*60*1000)
return expr.toGMTString()
}
function makeCookie(name, data, noDays){
var cookieStr = name + "="+ data
if (makeCookie.arguments.length > 2){
cookieStr += "; expires=" + getCookieExpireDate(noDays)
}
document.cookie = cookieStr
}

Let's examine the makeCookie() function. This function can be used to make a
temporary cookie like our first two or it can be used to make a cookie that will
javascriptmall.com/learn/lesson13.htm 5/7
10/11/2009 Learning JavaScript - Menus and Cooki…
persist on a hard drive for a given number of days. This works because
JavaScript functions can have a variable number of arguments.

The line if (makeCookie.arguments.length > 2){ tests the number of


arguments that the function has and if it has 3 or more then the expires argument
is set. If there are only two arguments, then the cookie is temporary and the
expires attribute is not set. Note that one argument would in this case cause a
JavaScript error because the data variable is expected but would not be
defined whereas two or more arguments will not cause any errors.

The getCookieExpireDate() function adds the supplied number of days to


today's date and then returns the results as a GMT string.

I used 1 day as the time that the cookie will remain on your hard drive in our
example above. So you might want to confirm this by checking later on today or
tomorrow. Remember that cookies remain in memory until you close your
browser.

I think that you will find that the above function and the one in the next paragraph
will work for most simple cookie situations that you will be doing.

There might be a time when you want to delete a cookie from a hard drive. In that
case just set the expires argument to a value prior to the current date. Calling the
makeCookie() function with a negative argument for the number of days should
work just fine.

How to Extract the Data from a Particular Cookie


Remember that a cookie is a string. Therefore to get the data from individual
cookies, you will need to use some of the string methods (refer to lesson 7 and
the Library for more information).

Here is the function that I use to extract data from cookies.

function readCookie(cookieName){
var searchName = cookieName + "="
var cookies = document.cookie
var start = cookies.indexOf(cookieName)
if (start == -1){ // cookie not found
return ""
}
start += searchName.length //start of the cookie data
var end = cookies.indexOf(";", start)
if (end == -1){
end = cookies.length
}
return cookies.substring(start, end)
}

You pass it the name of a cookie and it returns the data that is contained in the
cookie. Hopefully, by now you can look at the function and analyze what is
happening for yourself. Therefore, I don't plan on discussing it any further here.

You can prove that this function does indeed work by clicking on each of the
buttons below to extract the data from each cookie you created above.

Read Cookie 1 Read Cookie 2 Read Cookie 3

javascriptmall.com/learn/lesson13.htm 6/7
10/11/2009 Learning JavaScript - Menus and Cooki…

Note that only the name and the data (name-data pair) is available to you using
JavaScript. Other data such as the expiration date is not available.

More about the attributes of a Cookie


A cookie has one required attribute, name. It has four optional attributes, expires,
path, domain, and security.

We have learned about two of the cookie attributes, the required name attribute
and the optional expires attribute.

By default, a cookie is assessable to the web page that created it and any other
web pages that are contained in its same directory including the sub directories.
The path and domain attributes allow you to specify additional directories and
servers that can access your cookies.

The security attribute determines how a cookie is transmitted over a network.


This is set to insecure by default.

The last three attributes are beyond the scope of this class. If you want to know
more about them, then look in our library or read the technical details of cookies
from netscape

Assignment
1. Develop a simple website that contains a few pages. Use a drop down
list menu to navigate between the pages.
Solution

2. Show how something similar to problem 2 in lesson 11 and problem 1 in


lesson 12 can be accomplished using cookies. Make a form that
requests some information and then display a new page containing that
information when a button on the form is pressed.
Solution Source - Enter Info Results

Check this Freebie out!


I n t e rn e t A cce ss - Fre e Tria ls a n d S p e cia ls
NetZero, Juno, PeoplePC, EarthLink, AOL and more!

[ Top of Page | Contents ]

© 1999 - 2004 by Ray Stott - All Rights Reserved.

javascriptmall.com/learn/lesson13.htm 7/7

You might also like