--------
Lesson 11
An array is a group. An array is also an object and as an object, it has properties. There are built in arrays, such as all the images on a page. Have a look at this...
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="Javascript"><!-- function ShowSource(position) function NumberofImages() //--></SCRIPT> </HEAD> <CENTER> <FORM NAME="form01"> <A HREF="javascript:NumberofImages()">Click here</A> for number of images on this page. </CENTER> </BODY> |
Lesson 12
Another "built in" array is the options array in a drop down list. Consider the following list...
Its HTML is as follows...
<FORM NAME="form02"> <SELECT NAME="bradykids"> <OPTION VALUE="greg" >Greg <OPTION VALUE="marsha">Marsha <OPTION VALUE="peter" >Peter <OPTION VALUE="jan" >Jan <OPTION VALUE="bobby" >Bobby <OPTION VALUE="cindy" >Cindy </SELECT> </FORM> |
Notice the list has a name and each option has a value.
Look at the following script...
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="Javascript"><!-- function GoBrady() //--></SCRIPT> </HEAD> <FORM NAME="form02"> </BODY> |
It uses the event handler
onChange. When the state of the drop down list changes it
invokes the function GoBrady(). This function throws up an alert box displaying
the
selectedIndex property of the options array. Fiddle with it until you understand
what's
going on.
Alrighty, we can easily get the index of the selected Brady. But, how can we get the value? Well, where the selectedIndex is a property of the array, the values are properties of the individual options. Does that make sense?
Remember when we were looking at image arrays and we said that the first image in the array is images[0], the second is images[1] and so forth? Well, the options array is similar. We named our array bradykids, so the first option is bradykids[0], the second is bradykids[1], the third is bradykids[2], etc. In the last script we grabbed the selectedIndex and stored it in the variable brady. So, we could get properties of individual options with bradykids[brady]. Have a look at this modified version of the last script...
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="Javascript"><!-- function GoBrady() //--></SCRIPT> </HEAD> <FORM NAME="form02"> </BODY> |
Lesson 13
Another object that we may have occasion to use is the location object. The location object is a property of the window object...
window.location
And, like other objects,
it has properties. One commonly used property is the href
property...
window.location.href
This specifies the URL of the document in that particular window.
Look at this script...
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="Javascript"><!-- function ShowUrl() function GoUrl() //--></SCRIPT> </HEAD> <A HREF="javascript:ShowUrl()">Click here</A>
for this document's URL.<BR> </BODY> |
We can define our own arrays. Let's suppose we want to define an array of colors...
colors
red
blue
green
yellow
purple
orange
First we would declare a new array...
colors = new Array();
Then define the individual elements of the array...
colors = new Array();
colors[0] = "red";
colors[1] = "blue";
colors[2] = "green";
colors[3] = "yellow";
colors[4] = "purple";
colors[5] = "orange";
Again, note the zero-based
counting scheme. The colors array above has 6 elements,
and we can reference each by number. Consider the following...
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="Javascript"><!-- colors = new Array(); function GetMyColor() //--></SCRIPT> </HEAD> <A HREF="javascript:GetMyColor()">Click here for my color</A> </BODY> |
Lesson 14
Let's suppose we send the function a color...
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="Javascript"><!-- colors = new Array(); function GetMyColor(mycolor) //--></SCRIPT> </HEAD> <A HREF="javascript:GetMyColor(3)">Click here for my color</A> </BODY> |
Lesson 15
Comments.
This is an HTML comment: <!-- Comment -->
This is a javascript comment:
/* Comment */
Everything between the /* and the */
is ignored. This can spread over multiple
lines...
/*************************************************
- This is all comments
here.
- You can write all kinds of stuff in a comment
like this.
**************************************************/
This is another javascript
comment: // Comment
It's a single line comment. Everything on that line after the //
is ignored.
document.write()
You can use javascript to
write to the page...
<HTML> <HEAD> <TITLE></TITLE> </HEAD> <BODY> <SCRIPT language="Javascript"><!-- document.write("Hello Joe!"); //--></SCRIPT> </BODY> |
Technically, this is the write method of the document object. And technically it should be window.document.write(), but the browser is smart enough to know that the document is in a window so you can leave it off. Later on we'll be messing with other windows and frames, and then we'll start to worry about it. But for now, while we're only talking about a single document in a single window, we can skip the window part.
Can we output HTML tags?
<HTML> <HEAD> <TITLE></TITLE> </HEAD> <BODY> <SCRIPT language="Javascript"><!-- document.write("<CENTER><I><B>Hello Joe!</B></I></CENTER>"); //--></SCRIPT> </BODY> |
There is a potential problem here though. Consider the following...
<HTML> <HEAD> <TITLE></TITLE> </HEAD> <BODY> <SCRIPT language="Javascript"><!-- document.write("And God said, "Let there be light!""); //--></SCRIPT> </BODY> |
Got an error????
If you're using a later version of Netscape, javascript errors may not be so apparent. Rather than an 'in your face' error window, the error may be quietly logged to a "javascript console" (not to be confused with the "java console"). The javascript console is accessed by typing javascript: in the location bar. This is where your error messages are.
The nested quotes are confusing the browser. The fix is simple... whenever you want quotes as part of a string you must escape them by preceeding them with a backwards slash. Escaping a character in a string basically tells the browser that a particular character is next (a quotation mark in this case) and that it's part of the string and not part of the script.
Look at the re-worked script...
<HTML> <HEAD> <TITLE></TITLE> </HEAD> <BODY> <SCRIPT language="Javascript"><!-- document.write("And God said, \"Let there be light!\""); //--></SCRIPT> </BODY> |
This document.write bit is a really handy thing to have around. With it you can dynamically print part of your page. For example, I know that your name is asdfedf and you are 532 years old. (Remember the info you gave earlier?)
Have a look at this example...
<HTML> <HEAD> <TITLE></TITLE> </HEAD> <BODY> <SCRIPT language="Javascript"><!-- myname = "Joe"; document.write(myname); //--></SCRIPT> </BODY> |
When writing to the page you can have as many document.write() statements as you wish...
document.write("<P><B>A
poem for " + yourname + "...<BR></B>");
document.write("<I>Roses are red,<BR>");
document.write("Violets are blue,<BR>");
document.write("Javascript is fun,<BR>");
document.write("And so are you!,<BR></I>");
A poem for asdfedf...
Roses are red,
Violets are blue,
Javascript is fun,
And so are you!,
It works exactly like YOU writing to the page, except the script is doing the writing and you can insert variables. We will fiddle around with document.write() in later areas of this tutorial.
One more little bit that I want you to know about before we move on...
document.writeln()
document.write() simply
writes each line tacked on to the end of the last.
document.writeln() writes each line on a new line. Not super important unless
you
want to be able to read what the browser has written to the page. write() can
produce a jumbled (though perfectly workable) mess. writeln() generates more
tidy output.
Lesson 16
Javascript and frames together are a wonderful tool. They're a very powerful combination. Here are a few nifty examples of javascript and frames working together...
ColorPicker
:The script is in the left frame. When a change is detected (or a color
is chosen) it completely re-writes the right frame with javascript. Even when
the thing first
loads, the right frame is written using javascript.
Print
version order page :What you may not notice right away is that this order
page is actually a framed page. There is a top frame and bottom frame with a
height of 0. The scripting is in the master page and directs the two frames
below it. This order page uses a
form to gather mailing information, then uses javascript to check that the certain
fields were entered, the email address is valid, etc. It then uses javascript
to write a custom order page based on the user's input. You are welcome to try
it out. (Generating a printable order won't result in a sale unless you print
it out and send me a check, so play with it as you wish.)
GateKeeper
:When you try the GateKeeper example, you might notice that it's acually
made up of multiple frames with javascript choreographing events between them
and.
Javascript even does all the writing.
Handy Dandy Font Viewer :Again, dynamic page generation between frames. All controlled by javascript taking it's cue from user input.
Back when you
were learning about frames, you learned to NAME frames and TARGET
them. Well, javascript does exactly the same thing... only in javascript fashion.
Remember when we talked about an object hierarchy?
window.document.form.input.value
Windows and frames are similar. Consider this frameset...
<FRAMESET COLS="200,*">
<FRAME SRC="dir.html" NAME="leftframe">
<FRAME SRC="start.html" NAME="rightframe">
</FRAMESET>
The top level object is
window
Think of frames as a main
window with child windows within it. window is the main
window.
The left frame is a child of that window and we refer to it by name...
window.leftframe
Note that "leftframe" comes from the NAME of the frame. If you named your frame "hunnypot", you would reference it with window.hunnypot. The right frame is similar...
window.rightframe
Copy and save this as left.html...
<HTML> <HEAD> <TITLE></TITLE> </HEAD> <BODY> Click here </BODY> |
Copy and save this as right.html...
<HTML> <HEAD> <TITLE></TITLE> </HEAD> <BODY> </BODY> |
And this as master.html...
<HTML> <HEAD> <TITLE></TITLE> </HEAD> <FRAMESET COLS="200,*"> </HTML> |
Lesson 17
First let's
come up with a simple function that will write to the right frame. I've found
that when using javascript with frames, it is wise to put as much coding as
possible in
the topmost frameset page (master.html in this example). So re-open master.html
and add the following...
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="JavaScript"><!-- function RightWrite() } //--></SCRIPT> </HEAD> <FRAMESET COLS="200,*"> </HTML> |
So far just
an empty function. Now let's write my name to the right frame.
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="JavaScript"><!-- function RightWrite() //--></SCRIPT> </HEAD> <FRAMESET COLS="200,*"> </HTML> |
See what we're doing here? Basically it's a simple document.write() thing except we're telling the document to do it to the document that resides in the rightframe. There are also a couple other lines that are necessary when writing to a window (or frame). First we clear() it, then we open() it then we write() to it, then we close() it.
We're not quite done yet. We have to make the link that calls the function. Re-open left.html and add the following...
<HTML> <HEAD> <TITLE></TITLE> </HEAD> <BODY> <A HREF="javascript:top.RightWrite()">Click here</A> </BODY> |
Study that last example until you understand exactly what's going on.
One thing that should be
noted is that we just wrote "Joe" to the document, not any
HTML tags. If you look at the source of that frame after it's written, you will
simply
find "Joe"... no <HTML>, <HEAD> or <BODY> tags.
That stuff would only be there if we
wrote it as well...
window.rightframe.document.clear();
window.rightframe.document.open();
window.rightframe.document.write("<HTML>");
window.rightframe.document.write("<HEAD><TITLE></TITLE></HEAD>");
window.rightframe.document.write("<BODY>");
window.rightframe.document.write("Joe");
window.rightframe.document.write("</BODY>");
window.rightframe.document.write("</HTML>");
window.rightframe.document.close();
While it's usually a fine
idea to write a complete HTML document, we can probably
skip it for now for the sake of simplicity.
Lesson 18
Javascript has a "Math" object. It is used whenever we want to do anything more than simple arithmetic. It's basic syntax is Math.method(number). I know it's a little confusing at first... bear with me.
Look at this simple script
that calculates square root...
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="Javascript"><!-- function mySquareRoot() //--></SCRIPT> </HEAD> <A HREF="javascript:mySquareRoot()">Click here</A> </BODY> |
Lesson 19
The for statement is a very useful tool. Here is an example...
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="Javascript"><!-- function boxPopper() //--></SCRIPT> </HEAD> <A HREF="javascript:boxPopper()">Click here</A> </BODY> |
Here's what's happening...
1.for ( x = 0; x < 5;
x++ ) - x starts at 0
2.for ( x = 0; x < 5; x++ ) - if x is less than 5, execute the instructions
in the
brackets once... alert(x);
3.for ( x = 0; x < 5; x++ ) - increment x by one and go to step 2
The loop stops when x is
no longer less than 5. (You might be thinking... hey, the loop
stopped after 4! To which I ask you... is 5 less than 5? If you say yes, keep
thinking
about it until you say no ;-)
Lesson 20
A common type
of form element is the radio button. Consider the following script...
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="javascript"><!-- function FruitBox() //--></SCRIPT> </HEAD> <FORM NAME="myform"> </BODY> |
There are a few things to understand here. One, notice that while there are three separate elements, the three radio buttons share a name, therefore they have only one value. Even though we'll see that they can be individually referenced and manipulated, they are still a group and can even be thought of as a single input.
Also notice that when the page is first loaded, the value of that set of buttons is "undefined". (Even when we check a button via HTML the JS value still comes back as undefined. Go figure.) When we click one of the radio buttons, an onClick event handler sets the value of the group. When we click the link, the function simply reads the value that has been set by the onClick.
Lesson 21
We can dynamically
check and un-check radio buttons with javascript. The basic
syntax is:
button.checked
= true
or
button.checked = false
"checked" is a property of the radio button object. Have a look at this...
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="javascript"><!-- function FruitBox() //--></SCRIPT> </HEAD> <FORM NAME="myform"> </BODY> |
Here is what we have to this point...
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="javascript"><!-- function FruitBox(whichfruit) //--></SCRIPT> </HEAD> <FORM NAME="myform"> </BODY> |
Lesson 22
There are probably a couple ways to solve this problem. One solution would be to send two values to the function...
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="javascript"><!-- function FruitBox(whichfruit, fruitname) //--></SCRIPT> </HEAD> <FORM NAME="myform"> </BODY> |
Again, once you get past the most basic scripts, you'll find there are often several ways to acomplish the same thing. It is very important to understand that while arguments can be made that one way is better than another, or one way is less problematic than another, or one way is more efficient than another, the important thing is that it works. All other discussion falls behind "Does it get the job done?"
Let's take a small detour and look at this idea of sending a function more than one variable.
Consider the following...
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="javascript"><!-- function DoSomething(item1,item2) //--></SCRIPT> </HEAD> <A HREF="javascript:DoSomething(1,'roses')">Click here</A> </BODY> |
Each link should send the following info to a function... name, age, and favorite color. When you click on a link, I want an alert box to pop up with a statement like so...
Sonny is 36 years old and his favorite color is red.
Now, notice that it says "his" favorite color. Connie is female, so it should read "her" favorite color.
Lesson 23
You often need more than one function to write powerful scripts. A function is called and that function utilizes other functions.
Here is an example...
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="javascript"><!-- function SayHi() function GetName() //--></SCRIPT> </HEAD> <A HREF="javascript:SayHi()">Click here</A> </BODY> |
Remember a while back we talked about prompt boxes returning a value? Well I made this particular function do just that. Notice the "return" statement? This function is written to return the random number. It doesn't just generate the random number,it actually sends it back to whatever called it.
Consider the following...
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="javascript"><!-- // Random number generator. If max=3 then function returns 1,2 or 3 function GetNumber() //--></SCRIPT> </HEAD> <A HREF="javascript:GetNumber()">Click here</A> </BODY> |
Lesson 24
Using my random
number code, write a script that gets a random number between 1 and 100 when
you click on a link. If the number returned is less than 50, throw up one message
("Hey, 32 is less than 50."). If it's 50 or greater, throw up an alternate
message ("Yo, 77 is greater than or equal to 50.").
This is an example of creative problem solving. I've told you that programming
is ann exercise in logic. Well, it's just as much an exercise in problem solving...
how to trim that square peg so it fits neatly into the round hole.
Here is a simple function that might come in handy from time to time. Send it three numbers and it averages them...
function myAverager(num1,num2,num3) { averaged = ( (num1*1) + (num2*1) + (num3*1) ) / 3; } |
(We multiply each number by 1 just in case the browser thinks numX is a string. If we don't 13 + 39 might end up as 1339)
Notice that right now, the
function simply performs the arithmetic. It doesn't return anything. We can
make it return "averaged" by adding the following line...
function myAverager(num1,num2,num3) { averaged = ( (num1*1) + (num2*1) + (num3*1) ) / 3; return averaged; } |
Or even more simply...
function myAverager(num1,num2,num3) { return ( (num1*1) + (num2*1) + (num3*1) ) / 3; } |
Lesson 25 - Last one!
irt.org
:I can't stress
enough what a great javascript resource this is. Sure, they have
material on a wide range of Internet Related Technologies, but the section on
javascript beats all. Ever have a question or problem with javascript? If there's
an answer, you'll find it there.
Javascript Resources: Links to excellent javascript sites on the web.
For All These
Lessons I Thank 'pagetutor.com'