0% found this document useful (1 vote)
254 views71 pages

Javascript Tutor

The document is a tutorial on JavaScript lessons. It begins with a "Hello World" example, creating an HTML file with script tags and a JavaScript function that uses an alert box to display "Hello World!". It then explains variables in JavaScript and uses a variable to personalize the alert message. Finally, it adds a prompt box to ask the user for their name and displays a customized greeting using their input.

Uploaded by

Gigel Ion
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (1 vote)
254 views71 pages

Javascript Tutor

The document is a tutorial on JavaScript lessons. It begins with a "Hello World" example, creating an HTML file with script tags and a JavaScript function that uses an alert box to display "Hello World!". It then explains variables in JavaScript and uses a variable to personalize the alert message. Finally, it adds a prompt box to ask the user for their name and displays a customized greeting using their input.

Uploaded by

Gigel Ion
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 71

Javascript Tutorial - Lesson 1

You are here: Home Javascript Tutor Lesson 1

Javascript Tutor - Lesson 1


Let's start with a traditional Hello World! Seems every programming tutorial begins with that. Copy the following and save as hello.html
<html> <head> <title></title> </head> <body> </body> </html>

Then add script tags within the head section. The script tags tell the browser that some sort of scripting is contained between (in this case "javascript").
<html> <head> <title></title> <script type="text/javascript"> </script> </head> <body> </body> </html>

Again, our script tags are within the head section, not the body. Now we'll make a function. A function does something. It executes a series of instructions. We'll start with an empty shell...
<html> <head> <title></title> <script type="text/javascript"> function () { } </script> </head> <body> </body> </html>

We'll name our function HelloWorld. We'll add that, and an alert box that say's "Hello World!"...
<html> <head>

http://www.htmliseasy.com/javascript/lesson01.html[8/2/2011 3:37:46 PM]

Javascript Tutorial - Lesson 1

<title></title> <script type="text/javascript"> function HelloWorld() { alert ("Hello World!"); } </script> </head> <body> </body> </html>

Notice how the function is structured. The word function declaring that it is in fact, a function. The function name - HelloWorld. The parentheses ( ), these have a use that we'll get into later, and the curly brackets - { } that contain the set of instructions. So, that's it for the function in the head tags. It's just sitting there waiting for something to call it. How about we make it execute when we click on a link? Sounds good to me. Here's a generic link that points nowhere for now...
<html> <head> <title></title> <script type="text/javascript"> function HelloWorld() { alert ("Hello World!"); } </script> </head> <body> <a href="">Hello</a> </body> </html>

Make it point to our function...


<html> <head> <title></title> <script type="text/javascript"> function HelloWorld() { alert ("Hello World!"); } </script> </head> <body> <a href="javascript:HelloWorld()">Hello</a> </body> </html>

Now try it. Well, whaddya know about that? Your first javascript. Before we go on, there's something else we should make clear. Javascript and Java are two

http://www.htmliseasy.com/javascript/lesson01.html[8/2/2011 3:37:46 PM]

Javascript Tutorial - Lesson 1

completely different things. What we just did is Javascript, NOT Java. Java is a whole nuther thing. The only real thing the two have in common are the letters J-A-V-A in their name. Long long ago, in a land far away, Netscape made a new scripting language for their browser. They called it LiveScript. About that time, the Java programming language was gaining in popularity so the folks at Netscape renamed their scripting language to JavaScript to catch the Java wave. The two have been confused ever since. To add to the confusion, Microsoft saw that this scripting thing was pretty cool so they decided to incorporate it into their browser too. Except they call their flavor of javascript Jscript. (Gee, what a clever bunch.) Now, to further add to the confusion, not only are there differences between Netscape's javascript and Microsoft's Jscript, but because this scripting is an evolving technology, there can be even further differences between scripting support depending on what version of browser you're using... oh goodie. Well, here's the good news... most of the javascript you'll get into is simple basic stuff that is easily handled by the majority of modern browsers. And ALL of the scripting we'll touch on in this tutorial is easily handled by all the major browsers. And one more thing since I'm thinking about it... and it's VERY important...

JAVASCRIPT IS CASE-SENSITIVE
The function HelloWorld is not the same as helloworld. Be very careful about this. Case related errors can be frustrating because you get an error that says that MyVariable doesn't exist when there it is plain as day - myVariable. Understand?

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson01.html[8/2/2011 3:37:46 PM]

Javascript Tutorial - Lesson 2


You are here: Home Javascript Tutor Lesson 2

Javascript Tutor - Lesson 2


Variables.
What's a variable? Let's suppose x=5. x is a variable. The statement x=5 declares that the value of x is now 5. Can x be something else? Sure, x=6. Now x equals 6. (Hence the name "variable"... it's value can vary.) Can a variable be something other than a number? Sure. How about x="Joe". Now x equals the string "Joe". (A string by the way is a string of characters... and strings are always enclosed in quotes.) Can the name of a variable be something other than a letter like x? Sure, myname="Joe". Simple. How can we incorporate this new found knowledge into our function? Easy...
<html> <head> <title></title> <script type="text/javascript"> function HelloWorld() { myname = "Joe"; alert(myname); } </script> </head> <body> <a href="javascript:HelloWorld()">Hello</a> </body> </html>

Try it. (Note again that strings are always enclosed in quotes, but variables are not.) What we have called is the alert method. Think of a method as a command. Javascript has many methods. We could make it say Hello + variable...
<html> <head> <title></title> <script type="text/javascript"> function HelloWorld()

http://www.htmliseasy.com/javascript/lesson02.html[8/2/2011 3:37:32 PM]

Javascript Tutorial - Lesson 2

{ myname = "Joe"; alert("Hello " + myname); } </script> </head> <body> <a href="javascript:HelloWorld()">Hello</a> </body> </html>

Try it.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson02.html[8/2/2011 3:37:32 PM]

Javascript Tutorial - Lesson 3


You are here: Home Javascript Tutor Lesson 3

Javascript Tutor - Lesson 3


As I said before, Javascript is plenty powerful. We can go in any one of a dozen directions with this. What I'm going to do is wander around here and there, trying to touch on as many basic things as I can. I'll try to explain a little as we go. So, what now? Let's add a prompt box to ask our name and then spit out a personalized Hello message.
<html> <head> <title></title> <script type="text/javascript"> function HelloWorld() { myname = prompt("What's yer name bub?", ""); alert("Hello " + myname); } </script> </head> <body> <a href="javascript:HelloWorld()">Hello</a> </body> </html>

Try it. Ain't it cool? In the prompt box thing, the part that says "What's yer name bub?" is fairly self explanatory. But what are the empty double quotes ("") for? That's for the default string. Put something in the quotes (like "Sporto") and run it again to see the effect. Note also that we did something strange. We made the variable myname equal to the prompt method...
myname = prompt("What's yer name bub?", "");

Seem a little wierd? Well, what we're really saying is that the value of myname is whatever the prompt box returns. And it returns whatever you enter in the box. So, myname equals whatever you enter into the box. Get it? Remember before when I said we'd get back to the parentheses()? Well now's the time. First, we'll look at the end result, then come back and talk about what's going on.
<html> <head> <title></title>

http://www.htmliseasy.com/javascript/lesson03.html[8/2/2011 3:37:20 PM]

Javascript Tutorial - Lesson 3

<script type="text/javascript"> function HelloWorld(name) { alert("Hello " + name); } </script> </head> <body> <a <a <a <a href="javascript:HelloWorld('Joe')">Hello Joe</a><br> href="javascript:HelloWorld('Tom')">Hello Tom</a><br> href="javascript:HelloWorld('Frank')">Hello Frank</a><br> href="javascript:HelloWorld('Bob, Carol, Ted & Alice')">Hello to a few other people.</a>

</body> </html>

Try it. Do you see what's going on here? We're passing values to the function. name is a variable that is used in the function. When we pass 'Joe', or 'Tom' or whatever to the function, the function uses that in place of the variable name. This passing of variables is a very useful thing. We can write a function once and use it a thousand times and get a different result depending on what we pass to it. Also notice we used a single quote ' nested inside of a double quote "...
<a href="javascript:HelloWorld('Joe')">

Using the following will confuse the browser and generate an error.
<a href="javascript:HelloWorld("Joe")">

You can use single quotes or double quotes... doesn't matter. But when quotes are nested, it makes a HUGE difference. A good habit to get into is to use double quotes first. Use single quotes only for a nested set. Now, since the best way to learn is to learn by doing, I have something for you to do... Exercise: Make a web page and insert these three images...

Make it so that as you click on each number, an alert box pops up and says "You clicked on 1" (or 2, or 3). Here is a solution. There is something very important I must emphasize... 90% of your learning will come from doing these exercises. If you skip them, you won't get much out of this tutorial. If you suffer through each and every one, you'll slowly start to gain proficiency. Bear in mind it does come slowly. There aren't many geniuses in this world... the rest of us have to study hard and work at it. As you are presented with exercises, it's perfectly OK to click the solution link first to see the effect on a web page. This way you'll know exactly what I'm looking for. But don't cheat and look at the code. Try to figure it out for yourself first... I mean really try... then look at the code. Anyone can look at how I coded something and more or less understand it. I don't want you to just understand it... I want you to be able to DO it! Big difference.

Learn by doing

http://www.htmliseasy.com/javascript/lesson03.html[8/2/2011 3:37:20 PM]

Javascript Tutorial - Lesson 3

With all that in mind, here is another exercise... Exercise: Combine the prompt box with the last exercise so that with each click of a button, it asks you for your name and spits back something like "Hey Joe, you picked number 1." Here is a solution.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson03.html[8/2/2011 3:37:20 PM]

Javascript Tutorial - Lesson 4


You are here: Home Javascript Tutor Lesson 4

Javascript Tutor - Lesson 4


Events.
What's an event? An event is when something happens. Such as a mouse over, mouse click, page loading, etc. We could make a simple alert box pop up when the page loads using the onLoad event handler in the body tag...
<html> <head> <title></title> <script type="text/javascript"> function HelloWorld() { alert("Hello World!"); } </script> </head> <body onLoad="HelloWorld()"> Hello </body> </html>

Try it. Every time you load the page, the onLoad event handler is triggered. What else is there? Lots of people use onMouseOver event handlers in links. Here is the same example with a couple minor changes...
<html> <head> <title></title> <script type="text/javascript"> function HelloWorld() { alert("Hello World!"); } </script> </head> <body> <a href="" onMouseOver="HelloWorld()">Hello</a> </body> </html>

http://www.htmliseasy.com/javascript/lesson04.html[8/2/2011 3:28:09 PM]

Javascript Tutorial - Lesson 4

Try it. You'll notice that the link doesn't point to anything. That's not something we'd want to leave in a finished page, but for now, since we're just learning, we'll let it slide. We can also do an onMouseOut. The alert doesn't pop up until the mouse moves off of the link.
<html> <head> <title></title> <script type="text/javascript"> function HelloWorld() { alert("Hello World!"); } </script> </head> <body> <a href="" onMouseOut="HelloWorld()">Hello</a> </body> </html>

Try it. Yet another event handler is onClick...


<html> <head> <title></title> <script type="text/javascript"> function HelloWorld() { alert("Hello World!"); } </script> </head> <body> <a href="" onClick="HelloWorld()">Hello</a> </body> </html>

Try it. Exercise: Now it's your turn... make a page that uses the onLoad event handler to prompt you for your name, then says Hello Yourname!. Here is a solution. Can you have more than one function? Sure! You can have as many as you want. Just so you stay sane you might want to keep it as neat and organized as possible...
function HelloWorld() { alert("Hello World"); } function HelloStinky() { alert("Hello Stinky!"); }

http://www.htmliseasy.com/javascript/lesson04.html[8/2/2011 3:28:09 PM]

Javascript Tutorial - Lesson 4

Exercise: Now, knowing this, I want you to make a web page with two functions and those three red buttons. The first function asks for the user's name onLoad. Then, when the mouse passes over one of the three red buttons, a second function triggered by the mouseOver causes an alert to pop up with something like "Hello Joe. You moused over number 1". Here is a solution. You'll notice that once a value is assigned to a variable, it will stay in memory until it's either changed, or you exit the web page. Now I suppose is a good time to explain the semicolon (;) at the end of some of the lines. The semicolon should be used at the end of each instruction. It helps the browser know when one instruction ends and another one begins. You could also place multiple instructions on one line, separating each with a semi-colon...
instruction1; instruction2; instruction3;

is the same as
instruction1; instruction2; instruction3;

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson04.html[8/2/2011 3:28:09 PM]

Javascript Tutorial - Lesson 5


You are here: Home Javascript Tutor Lesson 5

Javascript Tutor - Lesson 5


Javascript is pretty good at math. Copy this and run it...
<html> <head> <title></title> <script type="text/javascript"> function MathThing() { firstnumber = prompt("Give me a number.", ""); secondnumber = prompt("Give me another number.", ""); total = firstnumber * secondnumber; alert(firstnumber + " x " + secondnumber + " = " + total); } </script> </head> <body> <a href="javascript:MathThing()">Click me</a> </body> </html>

Try it. It simply requests two numbers and multiplies them together. Note that in most programming languages, * means multiply. If we used x we would continually confuse it with the letter x. xxx (x times x) would raise a few eyebrows. Also, for the sake of simplicity, we haven't done any error checking. We do nothing to make sure that the user actually enters a number. He could very well enter Joe and 0%. This would result in...
Joe x 0% = NaN

(Not a Number)

As you go on to develop scripts for various purposes, you'll find that a big part of your task is dealing with errors. In other words, how can things go wrong and how do we handle it. Fortunately, we'll worry about that later. We'll keep things simple for now. Now try adding the numbers instead...
<html> <head> <title></title> <script type="text/javascript"> function MathThing() { firstnumber = prompt("Give me a number.", "");

http://www.htmliseasy.com/javascript/lesson05.html[8/2/2011 3:28:34 PM]

Javascript Tutorial - Lesson 5

secondnumber = prompt("Give me another number.", ""); total = firstnumber + secondnumber; alert(firstnumber + " + " + secondnumber + " = " + total); } </script> </head> <body> <a href="javascript:MathThing()">Click me</a> </body> </html>

Try it. Hmmm. Something's wrong... 3 + 6 = 36? Ok, we can see what's happening here but, what do we do about it? Well, if we suspect that a number might be regarded as a string instead of a number we could multiply each variable by 1. This would kinda force it into being a number. Some programming languages are very finicky about declaring at the outset whether a variable is a number, or a string, or whatever. Javascript is not so picky. If necessary, the browser will make an assumption. This makes it simpler for the programmer, but sometimes the browser assumes wrong and we have these little glitches to worry about. No biggie. You'll find it's a predictable glich. Or rather, it's not a glitch... it's a "feature". Try this instead...
<html> <head> <title></title> <script type="text/javascript"> function MathThing() { firstnumber = prompt("Give me a number.", ""); secondnumber = prompt("Give me another number.", ""); total = (firstnumber * 1) + (secondnumber * 1); alert(firstnumber + " + " + secondnumber + " = " + total); } </script> </head> <body> <a href="javascript:MathThing()">Click me</a> </body> </html>

Try it. That, ladies and gents, is a workaround. A workaround is a creative solution to a built-in shortcoming. You'll run into these little snags now and again, and you may have to come up with a workaround. Now think about something... doesn't it make sense that the majority of little snags you are likely to encounter have already been encountered (and subsequently solved) by others? Wouldn't it be nice to see how someone else may have solved your exact problem? Well, there are two resources that I want to introduce you to. The first is...

JavaScript FAQ at irt.org


http://www.htmliseasy.com/javascript/lesson05.html[8/2/2011 3:28:34 PM]

Javascript Tutorial - Lesson 5

For the beginning or even the experienced javascript programmer, this is one of the most valuable resources you'll find. It started out as Martin Webb's javascript FAQ and has evolved into a really incredible pile of useful information. Here you'll find answers to hundreds of scripting questions, all divided by category. The second resource is...

Google Groups (Advanced Search)


Google Groups is the latest and greatest archiver of all newsgroup discussions. Anything anyone has ever posted on any one of 30,000+ newsgroups is stored there and the search facilities are plenty strong. There happens to be a newsgroup called comp.lang.javascript where javascript related issues are discussed on a daily basis. Past discussions are searchable and are an incredible wealth of information. As a javascript programmer, it is in your very best interest to make full use of these two resources. Any problem you are likely to ever have has probably been had by others and the solution can almost certainly be found within these resources. Alrighty, back to math. Arithmetic operations are fairly consistent across most computer languages...
12 12 12 12 + * / 2 2 2 2

12 12 12 12

plus 2 minus 2 times 2 divided by 2

Javascript uses the standard order of operations...


6 + 3 * 4 = 18

It's not 36 because multiplication and division operations are done before addition and subtraction operations. If we wanted to add 6 + 3, then multiply the result by 4, we would use parentheses...
(6 + 3) * 4 = 36

Exercise: Write a page whereby when you click on a link, it asks you for a number. Then I want you to multiply that number by three and display it in an alert box like so: 5 * 3 = 15 Here is a solution. Exercise: Expand that page so that AFTER it alerts you to the answer, it asks you for ANOTHER number and adds THAT to the previous answer, and then pops up ANOTHER alert box with something like: (5 * 3) + 2 = 17 Here is a solution. Whew! That one was tough. I never said it was easy, but hey... this is how you learn. You'll pull out a lot of hair before you're through. As I've said before though, the more you practice, the easier it gets... I promise.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

http://www.htmliseasy.com/javascript/lesson05.html[8/2/2011 3:28:34 PM]

Javascript Tutorial - Lesson 5


QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson05.html[8/2/2011 3:28:34 PM]

Javascript Tutorial - Lesson 6


You are here: Home Javascript Tutor Lesson 6

Javascript Tutor - Lesson 6


Objects, properties and methods.
What's an object? An object in javascript is a window, a frame, an image, a form, a text box, the document itself, a radio button... you get the idea. What is a property? A property is some characteristic of an object... the location of a document, the background color of a document, whether a radio box is checked or unchecked, the width of an image, etc. What is a method? A method is basically a command. A method does something. For example, close() is a method. window.close() closes a window object. Not too much to it. This is a basic explanation of these three terms (object, property and method). In reality it can be a little more complicated than that, but for our purposes, it's clozenuff. So, what do we do with objects and properties and stuff?? Well, let's get a little more background. Take for example the text box below.

This is the HTML code for that form...


<form name="myform"> <input type="text" name="mytextbox" value=""> </form>

Follow me here. We have the browser window...


window

In the window is this document...


window.document

In the document is a form...


window.document.form

In the form is an input...


window.document.form.input

And the input has a value...


window.document.form.input.value

(Right this moment the value is nothing, but nothing is still a value.)

http://www.htmliseasy.com/javascript/lesson06.html[8/2/2011 3:28:51 PM]

Javascript Tutorial - Lesson 6

This is an object hierarchy. This is how you would refer to different properties of different objects on the page. An imaginary object hierarchy might be...
world.country.state.city.street.house.person.name

This would define the name property of that particular person. What about his height?
world.country.state.city.street.house.person.height

We could back up a little and say that population might be a property of the city object...
world.country.state.city.population

This is how you must begin to think about a simple web page if you're going to manipulate its objects and their properties. Now let's go back to the text box we saw earlier. It's HTML code again is
<form name="myform"> <input type="text" name="mytextbox" value=""> </form>

We can generically refer to a value contained in a text box with...


window.document.form.input.value

Now there's one more thing, a document can obviously contain more than one form, so one way to distinguish one form from another, is to name our forms. Note the form above is named myform. Same goes with form inputs. A form can have multiple inputs, so to specify one in particular, we will call it by name (in this case there's only one input and it's name is mytextbox). If we then use the name of the form and the name of the input, we can now call on that particular box's value by saying...
window.document.myform.mytextbox.value

Ok Joe, that was confusing (but interesting). But do tell, what the heck do we do with it now? Well, try this on for size...
<html> <head> <title></title> <script type="text/javascript"> function HelloBox() { alert(window.document.myform.mytextbox.value); } </script> </head> <body> <form name="myform"> <input type="text" name="mytextbox" value=""> </form> Enter something in the box and click <a href="javascript:HelloBox()">here</a>. </body> </html>

Try it. Pretty neat I'd say. Do you see what's going on? Study it until you do.

http://www.htmliseasy.com/javascript/lesson06.html[8/2/2011 3:28:51 PM]

Javascript Tutorial - Lesson 6

I'll jump ahead here and have you take a quick look at the JavaScript Authoring Guide included with this tutorial. In that reference, near the bottom of the left frame, you'll find links to Objects, Properties and Methods. It will give you an idea of some of the things you have to work with.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson06.html[8/2/2011 3:28:51 PM]

Javascript Tutorial - Lesson 7


You are here: Home Javascript Tutor Lesson 7

Javascript Tutor - Lesson 7


Exercise: Add to the last exercise. Make two text boxes. When you click on the link, have an alert box pop up with the contents of one text box, then a second alert box pop up with the contents of the other text box. Here is a solution. Exercise: make a page with 2 small text boxes side by side. Under the text boxes make 4 links... Add, Subtract, Multiply and Divide. When the user clicks on the Add link it should get the two numbers in the boxes, add them together and display the answer in an alert box as follows... 5 + 3 = 8. Do the same for each of the other operations. Here is a solution. Notice I say "Here is a solution" rather than "Here is the solution". When you start programming javascript you'll see that there is often more than one way to get the job done. While it could be argued that one way is "better" than another, in the end, what matters is that it works, and that it acomplishes the task at hand. When I first started programming, I always worried about doing things the "proper" way. One day it dawned on me... the "proper" way is whatever works. You can streamline things later if you wish, but as long as it gets the job done, it's good to go. Another property we can get or manipulate is the document's background color. Have a look at this...
<html> <head> <title></title> <script type="text/javascript"> function BgcolorGetter() { alert(window.document.bgColor); } </script> </head> <body bgcolor="#bbddcc"> Click <a href="javascript:BgcolorGetter()">here</a> for this document's background color. </body> </html>

Try it. bgColor is a property of the document object. Try messing around with the color in the body tag and see that it always returns the proper background color. Remove the bgcolor attribute from the body tag altogether and see what happens.

http://www.htmliseasy.com/javascript/lesson07.html[8/2/2011 3:29:04 PM]

Javascript Tutorial - Lesson 7

Can we set the bgColor? You betcha...


<html> <head> <title></title> <script type="text/javascript"> function BgcolorSetter(mycolor) { window.document.bgColor = mycolor; } </script> </head> <body> <a href="javascript:BgcolorSetter('#ff9999')">Red</a>&nbsp;&nbsp;&nbsp; <a href="javascript:BgcolorSetter('#99ff99')">Green</a>&nbsp;&nbsp;&nbsp; <a href="javascript:BgcolorSetter('#9999ff')">Blue</a> </body> </html>

Try it. Do you understand what's going on? Study it until you do. Exercise: Add 3 more color selections to the page. Also, add something whereby the original color of the page is recorded at the outset and add a seventh choice to set the color back to this default. Here is a solution. Note that in the previous (and following) solution the scripting is after the <body> tag. The reason for this is simple. After a little experimentation I noticed that some browsers record the bgColor at the point where the body tag loads. If you ask the browser to remember the bgColor before it reads the body tag, it cannot remember it and the script will act wierd. (A perfect example of why you should always test your scripts on a couple different browsers and why de-bugging is a large part of any programming effort.) Anyhow, the simple workaround is to place the script after the body tag. I know it's common practice to put scripting within the HEAD section, but that's only a suggested practice, it's not mandatory. Exercise: Make another page and insert the following images...

The hex color codes are on the images. Make it so that as the mouse passes over each image, the document background color changes accordingly. As the mouse moves off of each image, make the background color change back to the default. Here is a solution.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of Barebones HTML Guide Javascript Tutor - A solid GateKeeper - cool password protection with javascript that anyone can use

http://www.htmliseasy.com/javascript/lesson07.html[8/2/2011 3:29:04 PM]

Javascript Tutorial - Lesson 7


EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson07.html[8/2/2011 3:29:04 PM]

Javascript Tutorial - Lesson 8


You are here: Home Javascript Tutor Lesson 8

Javascript Tutor - Lesson 8


If-then statements.
If condition, do something.
if (condition) { do something; } if ( x > 4 ) { alert("Hey kids, x is greater than 4!"); }

Have a look at this...


<html> <head> <title></title> <script type="text/javascript"> function Hello() { x = 6; if ( x > 4) { alert("Hey kids, x is greater than 4!"); } } </script> </head> <body> <a href="javascript:Hello()">Click here</a> </body> </html>

Try it. Understand what's going on? Good. I thought so. An if-then statement is pretty simple to grasp. It is also one of the most powerful tools in your bag of tricks. This simple statement (and its variations) are the brains behind your programs. This is the computer making a decision. Exercise: Add a prompt box to the above page. When you click on a link, it asks the user for a number. If that number is greater than 4, you get an alert box saying something like "Hey kids, 8 is greater than 4!". Here is a solution. Adding to the if (then) statement is the if-else statement...
http://www.htmliseasy.com/javascript/lesson08.html[8/2/2011 3:29:17 PM]

Javascript Tutorial - Lesson 8

If condition, do something... Else, do something else.


if (condition) { do something; } else { do something else; } if ( x > 4 ) { alert("Hey kids, x is greater than 4!"); } else { alert("Hey kids, x is NOT greater than 4!"); }

Our example again. This time we'll make x = 3.


<html> <head> <title></title> <script type="text/javascript"> function Hello() { x = 3; if ( x > 4) { alert("Hey kids, x is greater than 4!"); } else { alert("Hey kids, x is NOT greater than 4!"); } } </script> </head> <body> <a href="javascript:Hello()">Click here</a> </body> </html>

Try it. Exercise: You guessed it. Add that feature to your last exercise. Here is a solution.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript

http://www.htmliseasy.com/javascript/lesson08.html[8/2/2011 3:29:17 PM]

Javascript Tutorial - Lesson 8


EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson08.html[8/2/2011 3:29:17 PM]

Javascript Tutorial - Lesson 9


You are here: Home Javascript Tutor Lesson 9

Javascript Tutor - Lesson 9


Nested if-then statements.
<html> <head> <title></title> <script type="text/javascript"> function Hello() { x = prompt("Give me a number",""); if (x == 6) { alert("Wow! " + x + " equals 6!"); } else { if ( x > 4) { alert("Hey kids, " + x + " is greater than 4!"); } else { alert("Hey kids, " + x + " is NOT greater than 4!"); } } } </script> </head> <body> <a href="javascript:Hello()">Click here</a> </body> </html>

Try it. First we test if x==6 (x equals 6) I'll explain the double equal sign in a minute. If x==6 then we get a message. If x does not equal 6 then we get a pair of if-then statements testing for greater than 4 or not greater than 4. Keep studying the example until you get it. About the double equal sign. Let me try to explain this way...
x = 6 x == 6

the value of x is now 6 (assignment) x equals 6 (comparing for equality)

x=6 is a statement that assigns the value 6 to the variable x. x==6 is a comparison test, very often used in an if statement... if x equals 6. = is an assignment operator

http://www.htmliseasy.com/javascript/lesson09.html[8/2/2011 3:29:28 PM]

Javascript Tutorial - Lesson 9

== is a comparison operator The difference between the two is very important. If you don't fully understand it yet, that's OK. Just keep in mind that there is a difference. Speaking of comparison operators....
x x x x x x > 6 < 6 >= 6 <= 6 != 6 == 6

x x x x x x

is greater than 6 is less than 6 is greater than or equal to 6 is less than or equal to 6 does not equal 6 equals 6

Exercise: Make a page that does the following: When you click on a link, a prompt box comes up and asks you for a number. If your number is less than 100, throw up an alert box saying what your number was... "Your number is 28". If your number is greater than 100, throw up an alert box that says "Oh my, your number is too big for me." If your number is exactly 100, throw up an alert box saying "Bingo, your number is exactly 100." Here is a solution. Exercise: Revise your last exercise to get the number from an input/text box rather than a prompt box. Here is a solution. Exercise: Revise the second last exercise (with the prompt box) so that if the number is less than 100 the page background turns YELLOW. If the number is greater than 100 the page background turns GREEN, if the number is equal to 100 the page turns to BLUE and throws up an alert box that says (Bingo!), and... if the number is greater than 500 the background turns RED and throws up another prompt box requesting a lower number and starts all over again. Hint: in order to "start all over again" the function will have to call itself. This is an exercise in logic. Programming is an exercise in logic. This is a lot heavier than cut-n-paste javascripting. This stuff will make your brain sore ;-) Here is a solution. Earlier, we were reading the value from a text box...
x = window.document.form.input.value;

We can also set the value of a text box...


<html> <head> <title></title> <script type="text/javascript"> function SetTheBox() { window.document.myform.mytextbox.value = 5; } </script> </head> <body> <form name="myform"> <input type="text" name="mytextbox" value="">

http://www.htmliseasy.com/javascript/lesson09.html[8/2/2011 3:29:28 PM]

Javascript Tutorial - Lesson 9

</form> <a href="javascript:SetTheBox()">Click here</a>. </body> </html>

Try it. Exercise: Alter the above example to get the value from a prompt box, and place it into the text box. Also, instead of a link to invoke the function, use an input of type button and use the onClick event...
<input type="button" onclick="myfunction()">

Here is a solution. Exercise: Make 3 text boxes like so...

=
Underneath make four buttons: Add, Subtract, Multiply and Divide. Make each button grab the numbers from the first two boxes, perform the appropriate calculation, and place the answer in the third box. Here is a solution. Exercise: To the last exercise, add a fourth box like so...

=
Alter the functions to place the proper operation symbol ( + - * / ) into that fourth box Here is a solution. You know, it occurs to me that you may be wondering why we're doing all this cheesy rinky-dink stuff when we could be learning cool things like how to make games or shopping carts or something. Well, think of it as laying bricks. We learn to lay a couple bricks this way, then that way, and hopefully, after we're done, you'll have some basic skills and you'll attempt a brick cathedral on your own. But until then, we practice with the cheesy rinky-dink stuff

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

http://www.htmliseasy.com/javascript/lesson09.html[8/2/2011 3:29:28 PM]

Javascript Tutorial - Lesson 9


ColorPicker Upload your page Practice exercises

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson09.html[8/2/2011 3:29:28 PM]

Javascript Tutorial - Lesson 10


You are here: Home Javascript Tutor Lesson 10

Javascript Tutor - Lesson 10


The while statement.
while (condition) { do stuff; }

Consider the following...


<html> <head> <title></title> <script type="text/javascript"> function Adder() { number = 1; while (number < 5) { alert(number + " is less than 5"); number = number + 1; } } </script> </head> <body> <a href="javascript:Adder()">Click here</a> </body> </html>

Try it. See what's going on here? Study the example until you do. While we're here, there's a little programming shortcut you might be interested in. It is very common to increment or decrement a number by 1. In the last example we wrote it as...
number = number + 1;

This can also be written as...


number++;

You'll see this a lot in javascript, plus it's fairly common in other programming languages as well. The same shorthand can also be used for subtraction...
number--;

is the same as
http://www.htmliseasy.com/javascript/lesson10.html[8/2/2011 3:29:39 PM]

Javascript Tutorial - Lesson 10

number = number - 1;

Exercise: Alter the example above to prompt the user for both the first and last number. And use the number++ shorthand notation. (When you run this, I wouldn't make your "spread" too large or you'll be clicking alert boxes for an hour.) Here is a solution. Notice I multiplied the prompt box by 1. This is so that all entries are forced into being numbers before we do anything with them. If we left that out, multi-digit numbers such as 12 are sometimes considered strings rather than numbers. Exercise: Alter your last exercise to check if the second number is larger than the first. If it's not, inform the user and have him try again. (Hint: You'll need to add an if-else statement in there.) Here is a solution.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson10.html[8/2/2011 3:29:39 PM]

Javascript Tutorial - Lesson 11


You are here: Home Javascript Tutor Lesson 11

Javascript Tutor - Lesson 11


Arrays.
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 type="text/javascript"> function ShowSource(position) { window.document.form01.input01.value = window.document.images[position].src; } function NumberofImages() { alert(window.document.images.length); } </script> </head> <body> <center> <a href="" onMouseOver="ShowSource(0) "><img alt="img" hspace="4" border="0"></a> <a href="" onMouseOver="ShowSource(1) "><img alt="img" hspace="4" border="0"></a> <a href="" onMouseOver="ShowSource(2) "><img alt="img" hspace="4" border="0"></a> <a href="" onMouseOver="ShowSource(3) "><img alt="img" hspace="4" border="0"></a> <a href="" onMouseOver="ShowSource(4) "><img alt="img" hspace="4" border="0"></a> <a href="" onMouseOver="ShowSource(5) "><img alt="img" hspace="4" border="0"></a><br> <a href="" onMouseOver="ShowSource(6) "><img alt="img" hspace="4" border="0"></a> <a href="" onMouseOver="ShowSource(7) "><img alt="img" hspace="4" border="0"></a> <a href="" onMouseOver="ShowSource(8) "><img alt="img" hspace="4" border="0"></a> <a href="" onMouseOver="ShowSource(9) "><img alt="img" hspace="4" border="0"></a> <a href="" onMouseOver="ShowSource(10)"><img alt="img" hspace="4" border="0"></a> <a href="" onMouseOver="ShowSource(11)"><img alt="img" hspace="4" border="0"></a> src="food_icons/beer.gif" src="food_icons/burger.gif" src="food_icons/butter.gif" src="food_icons/carrot.gif" src="food_icons/cheese.gif" src="food_icons/cherries.gif" src="food_icons/hotdog.gif" src="food_icons/icecream.gif" src="food_icons/lemon.gif" src="food_icons/pizza.gif" src="food_icons/salad.gif" height="32" width="32" height="32" width="32" height="32" width="32" height="32" width="32" height="32" width="32" height="32" width="32" height="32" width="32" height="32" width="32" height="32" width="32" height="32" width="32" height="32" width="32"

src="food_icons/sammawich.gif" height="32" width="32"

<form name="form01"> <input type="text" name="input01" value="" size="70"> </form> <a href="javascript:NumberofImages()">Click here</a> for number of images on this page. </center>

http://www.htmliseasy.com/javascript/lesson11.html[8/2/2011 3:29:49 PM]

Javascript Tutorial - Lesson 11

</body> </html>

Try it. This demonstrates (more or less) the image array. The image array is an array of all the images on a page: images[]. The browser isn't necessarily interested in what the pictures are, so it numbers them, starting with 0. The first image is images[0], the second is images[1], the third is images[2], etc. The array as a whole has properties, one of which is length. This is demonstrated in the text link that throws up the number of images on the page. Each individual image also has properties of its own, such as src (source). This is demonstrated by the function ShowSource(). We pass the index number to the function and it displays that image's source in the text box. Understand that arrays can be a little confusing, so if it seems a little foggy, that's normal. It will sink in soon. Exercise: Alter the previous example so that there are only the images on the page. When the user clicks on an image, an alert box pops up with something like this...
You picked image indexed 3 out of 12 total images. It's source is C:\path\path\burger.gif

Even though you know there are 12 total images on the page, I don't want you to hard code "12" into the function. I want you to get that number from the length property of the image array object. Here is a solution. Another property of individual images is the name property. In an image tag, we can give an image a name like so...
<img src="mypic.gif" height="32" width="32" name="myimg">

We can then use it in a script (for example, to get that image's source)...
window.document.images["myimg"].src

Notice that now we have two ways to specify a particular image in the image array... by number, or by name. Study on that until you understand it. Exercise: Make a new web page using the 12 food icons. Give each image a name. Make it so that when the user clicks on an image, an alert box pops up with that image's source. Get the source by referencing the image by name, not by index number. Here is a solution. We passed the image name to the function. The function then used it to determine the source of that image. Keep studying the example until it's clear. Hint: use a single quote ' inside of a double quote ". Here is an example...
<a href="javascript:myFunc('joe')">

Using the following will confuse the browser and generate an error.
<a href="javascript:myFunc("joe")">

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

<< BACK

NEXT >>

http://www.htmliseasy.com/javascript/lesson11.html[8/2/2011 3:29:49 PM]

Javascript Tutorial - Lesson 11


Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson11.html[8/2/2011 3:29:49 PM]

Javascript Tutorial - Lesson 12


You are here: Home Javascript Tutor Lesson 12

Javascript Tutor - Lesson 12


Another "built in" array is the options array in a drop down list. Consider the following list...
Greg Greg

It's 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 (bradykids) and each option has a value. Look at the following script...
<html> <head> <title></title> <script type="text/javascript"> function GoBrady() { brady = window.document.form02.bradykids.selectedIndex; alert(brady); } </script> </head> <body> <form name="form02"> <select name="bradykids" onChange="GoBrady()"> <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> </body> </html>

Try it. 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

http://www.htmliseasy.com/javascript/lesson12.html[8/2/2011 3:30:02 PM]

Javascript Tutorial - Lesson 12

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 options 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]. Do I still have you or are you hopelessly confused? Have a look at this modified version of the last script...
<html> <head> <title></title> <script type="text/javascript"> function GoBrady() { brady = window.document.form02.bradykids.selectedIndex; alert(window.document.form02.bradykids[brady].value); } </script> </head> <body> <form name="form02"> <select name="bradykids" onChange="GoBrady()"> <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> </body> </html>

Try it. Keep studying it until you understand it.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

http://www.htmliseasy.com/javascript/lesson12.html[8/2/2011 3:30:02 PM]

Javascript Tutorial - Lesson 12


ColorPicker Upload your page Practice exercises

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson12.html[8/2/2011 3:30:02 PM]

Javascript Tutorial - Lesson 13


You are here: Home Javascript Tutor Lesson 13

Javascript Tutor - 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, the location object 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 type="text/javascript"> function ShowUrl() { alert(window.location.href); } function GoUrl() { window.location.href = "otherpage.html"; } </script> </head> <body> <a href="javascript:ShowUrl()">Click here</a> for this document's URL.<br> <a href="javascript:GoUrl()">Click here</a> to go to another page. </body> </html>

Try it. The function ShowUrl() gets the location and displays it in an alert box. The function GoUrl() sets the window's location to something else thereby causing that other page to load in the window. Exercise: Make 6 separate little web pages for each of the Brady kids. Something like this is fine. Alter the last exercise and instead of an alert box throwing up the value "bobby", change the value to the url of bobby's page (bobby.html, or whatever you name it.) Then, get that value and set that as the window's new href. The result is a nifty jump box. Here is a solution.

http://www.htmliseasy.com/javascript/lesson13.html[8/2/2011 3:30:31 PM]

Javascript Tutorial - Lesson 13

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 type="text/javascript"> colors = new Array(); colors[0] = "red"; colors[1] = "blue"; colors[2] = "green"; colors[3] = "yellow"; colors[4] = "purple"; colors[5] = "orange"; function GetMyColor() { alert(colors[2]); } </script> </head> <body> <a href="javascript:GetMyColor()">Click here for my color</a> </body> </html>

Try it. While it's certainly not the most useful script in the world, it does demonstrate a new Array() quite nicely. Understand what's going on here before you continue.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

http://www.htmliseasy.com/javascript/lesson13.html[8/2/2011 3:30:31 PM]

Javascript Tutorial - Lesson 13


QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson13.html[8/2/2011 3:30:31 PM]

Javascript Tutorial - Lesson 16


You are here: Home Javascript Tutor Lesson 16

Javascript Tutor - Lesson 16


Javascript and frames.
Javascript and frames together are a wonderful tool. They can be a very powerful combination. 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> </html>

Copy and save this as right.html...


<html> <head> <title></title> </head>

http://www.htmliseasy.com/javascript/lesson16.html[8/2/2011 3:31:30 PM]

Javascript Tutorial - Lesson 16

<body> </body> </html>

And this as master.html...


<html> <head> <title></title> </head> <frameset cols="200,*"> <frame src="left.html" name="leftframe"> <frame src="right.html" name="rightframe"> </frameset> </html>

Try it. What we're going to do is make a link in the left frame write to the document in the right frame. Oh, and while I'm thinking about it, using this method you can only write to a document, you can't go back into an already rendered document and re-write write a portion. If you need to re-write a portion of the document, you must re-write the whole thing from the beginning. Now, that said, there are some groovy DHTML techniques that allow manipulation of an already written document, but that is beyond the scope of a basic Javascript tutorial. We'll get into that another day.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson16.html[8/2/2011 3:31:30 PM]

Javascript Tutorial - Lesson 14


You are here: Home Javascript Tutor Lesson 14

Javascript Tutor - Lesson 14


Let's suppose we send the function a color...
<html> <head> <title></title> <script type="text/javascript"> colors = new Array(); colors[0] = "red"; colors[1] = "blue"; colors[2] = "green"; colors[3] = "yellow"; colors[4] = "purple"; colors[5] = "orange"; function GetMyColor(mycolor) { alert(colors[mycolor]); } </script> </head> <body> <a href="javascript:GetMyColor(3)">Click here for my color</a> </body> </html>

Try it. Exercise: Add a prompt box to the last example to get a number from a user. Ask the user for a number between 0 and 5. Use that number to grab an element from the array. (Technically I suppose we would ask for an integer between and including 0 and 5, but that sounds confusing. We'll just keep it a number between 0 and 5 and figure we all understand what we're talking about.) Here is a solution. Exercise: Add to your last exercise an if-else statement that catches any entry greater than 5 and asks again for a number between 0 and 5. Here is a solution. Notice that the last couple examples hard code the number 5 into the function. If we were to add colors, we would have to go through the function and change all references to "5". Surely there's a better way. Here's an idea... let's get that number into a variable... Exercise: Use the length property of an array to get the number of elements into a variable, then use that variable in the function. This is a tough exercise. Make sure you test your script thoroughly to reveal any errors.

http://www.htmliseasy.com/javascript/lesson14.html[8/2/2011 3:30:44 PM]

Javascript Tutorial - Lesson 14

Here is a solution. I suppose this is a good time for a little side track. Our latest script checks if a number is greater than 5 (or whatever). This script could also benefit from a bit that checks if the number is less than 0. In other words check if the number is greater than 5 OR less than 0. Consider this simple if statement...
if (x > 5) { do something }

It checks to see if x is greater than five. We can add another condition and test if x > 5 or x < 0...
if ((x > 5)||(x < 0)) { do something }

The OR operator is two vertical slashes (pipes)... ||. Exercise: Add this feature to your last exercise. Make the script check if the number is not greater than 5 or less than 0. Here is a solution. Similar to the OR operator is the AND operator. This operator is two ampersands... &&
if ((x > 5)&&(x < 0)) { do something }

The above basically says if x is greater than 5 and x is less than 0 then do something. Obviously no number can fit these conditions, but hopefully you still understand the concept. Exercise: Write a small script from scratch. When the user clicks on a link, a prompt box is thrown up that asks for a particular number (such as "Please enter 4"). A second prompt box then comes up asking for a second number (such as "Please enter 5"). The script is to determine if the user actually entered 4 and 5 as instructed. If correct, the user gets rewarded with a positive message. If not, a negative message. Utilize the && operator in your solution. Hint: remember to test for equality using a double equal sign ==. Here is a solution.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc.

http://www.htmliseasy.com/javascript/lesson14.html[8/2/2011 3:30:44 PM]

Javascript Tutorial - Lesson 14


Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson14.html[8/2/2011 3:30:44 PM]

Javascript Tutorial - Lesson 15


You are here: Home Javascript Tutor Lesson 15

Javascript Tutor - Lesson 15


/* Comments */
This is an HTML comment:
<!-- Comment --> /* Comment */ */

This is a javascript 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 type="text/javascript"> document.write("Hello Joe!"); </script> </body> </html>

Try it. 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>

http://www.htmliseasy.com/javascript/lesson15.html[8/2/2011 3:31:17 PM]

Javascript Tutorial - Lesson 15

<title></title> </head> <body> <script type="text/javascript"> document.write("<center><i><b>Hello Joe!</b></i></center>"); </script> </body> </html>

Try it. There is a potential problem here though. Consider the following...
<html> <head> <title></title> </head> <body> <script type="text/javascript"> document.write("And God said, "Let there be light!""); </script> </body> </html>

Try it.

Hmmm. Error.
With some browsers/configuations, errors may not be so apparent. You may see a popup error window, or the error may be silent. Internet Explorer based browsers may or may not throw up an error box. Either way though, in the case of a javascript error, you'll see a little yellow icon in the lower left corner of the window. Clicking on that will pop up the error message. Firefox users can access a "javascript console" by clicking Tools/JavaScript Console on the menu. It can also be accessed by typing javascript: in the location bar. Netscape users don't have a menu item like Firefox, but they too can type javascript: into the location bar to bring up the console. Ok, back to our error. 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 type="text/javascript"> document.write("And God said, \"Let there be light!\""); </script> </body> </html>

Try it.

http://www.htmliseasy.com/javascript/lesson15.html[8/2/2011 3:31:17 PM]

Javascript Tutorial - Lesson 15

This document.write() bit is a very handy thing to have around. With it you can dynamically print part of your page. For example, I know that your name is Ana and you are 30 years old. (Remember the info you gave earlier?) Have a look at this example...
<html> <head> <title></title> </head> <body> <script type="text/javascript"> myname = "Joe"; document.write(myname); </script> </body> </html>

Try it. It simply writes the variable myname to the page. Exercise: use a prompt box to get a name, then write it to the page like this... Hello Joe! Here is a solution. When writing to the page you can have as many document.write() statements as you wish...
document.write("<p>"); document.write("<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!</i>"); document.write("</p>");

A poem for Ana... 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, where 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.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

http://www.htmliseasy.com/javascript/lesson15.html[8/2/2011 3:31:17 PM]

Javascript Tutorial - Lesson 15

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson15.html[8/2/2011 3:31:17 PM]

Javascript Tutorial - Lesson 17


You are here: Home Javascript Tutor Lesson 17

Javascript Tutor - 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 type="text/javascript"> function RightWrite() { } </script> </head> <frameset cols="200,*"> <frame src="left.html" name="leftframe"> <frame src="right.html" name="rightframe"> </frameset> </html>

So far just an empty function. Now let's write my name to the right frame.
<html> <head> <title></title> <script type="text/javascript"> function RightWrite() { window.rightframe.document.open(); window.rightframe.document.write("Joe"); window.rightframe.document.close(); } </script> </head> <frameset cols="200,*"> <frame src="left.html" name="leftframe"> <frame src="right.html" name="rightframe"> </frameset> </html>

See what we're doing here? Basically it's a simple document.write() thing except we're telling the document to write to the document that resides in the rightframe. There are also a couple other lines that are necessary when writing a document to a window (or frame). First we open() the document for writing, then we write() to it, then we close() the document.

http://www.htmliseasy.com/javascript/lesson17.html[8/2/2011 3:31:50 PM]

Javascript Tutorial - Lesson 17

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> </html>

Note we call the function using top.RightWrite(). If we simply said RightWrite() the browser would look for the function in the same frame/document as the link that called it. But since our function resides in the topmost frameset, we must specify top.RightWrite(). A little confusing maybe, but not too too difficult. Try it. 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.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. I want to take a moment to mention a useful tidbit of information. If you use document.write() to write HTML tags, and then you attempt to validate that document, the validator may trip over the closing tags in the script...
window.rightframe.document.write("<b>Joe</b>");

The workaround is to escape the slashes in those closing tags...


window.rightframe.document.write("<b>Joe<\/b>");

As far as the browser is concerned, it's all the same thing, but as far as the validator is concerned, you have corrected the... um... "error". Exercise: Alter the previous example to send a value to the function from the link. Hint: you'll run into the nested quotes problem again, although this time it's a little different. The fix here is to use single quotes ' for the value you wish to pass...
<a href="javascript:top.RightWrite('Frank')">Click here</a>

While the browser is confused by nested quotes, it can handle a set of single quotes within a set of double quotes. Here is a solution. Exercise: Find a way to throw up a prompt box that asks for a name (or whatever) and then writes that user input to the right frame.

http://www.htmliseasy.com/javascript/lesson17.html[8/2/2011 3:31:50 PM]

Javascript Tutorial - Lesson 17

Here is a solution. Exercise: Expand on your last exercise by also asking for not only the user's name, but throw up additional prompt boxes asking for his age and a hex background color (such as cc99ff). Re-write the right frame to say something like "Paul is 22 years old" and make the document render with the chosen background color (do it by writing a <body> tag, don't just change the color via javascript). While you're at it, place a default color in the prompt box like so. Here is a solution. Exercise: Instead of throwing up prompt boxes, use a simple form with 3 input boxes and a button. When the button is pressed, values are snagged from the inputs and used to re-write the right frame. Here is a solution. Be persistent with this one. It draws on several items we've learned in previous lessons and is not as simple as it appears. If it doesn't work, you'll find clues in the error messages that are generated. Hint: I find the error messages generated by Firefox & Netscape are FAR more useful than those generated by Internet Explorer. Very often I use Firefox as an authoring environment, then check pages and scripts in Explorer. Hang in there until you complete this exercise and get it to work as expected. If you must, go ahead and have a look at the example's code, but understand what's going on. Some of the most useful and intensive learning comes when you are struggling with some problem. Reminds me of a line from Dog Day Afternoon... "Can't you see I'm dyin' over here?" You'll do your best learning when you're "dyin'". Exercise: Using simple math in the script, calculate how many hours old the user is and add that to your page re-write. Something like "That's over 1000 hours old!" Here is a solution.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson17.html[8/2/2011 3:31:50 PM]

Javascript Tutorial - Lesson 18


You are here: Home Javascript Tutor Lesson 18

Javascript Tutor - Lesson 18


Math.
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 that's a little confusing at first, but bear with me. Look at this simple script that calculates square root...
<html> <head> <title></title> <script type="text/javascript"> function mySquareRoot() { mynumber = Math.sqrt(9); alert(mynumber); } </script> </head> <body> <a href="javascript:mySquareRoot()">Click here</a> </body> </html>

Try it. See what's going on here? It's not too hard at all. Exercise: Alter the last example to throw up a prompt box that requests a number. Calculate the square root then throw an alert box up that says something like "The square root of 9 is 3" Here is a solution. Here's another Math method... Math.round() It... uh... rounds a number to the nearest integer. (Aren't you glad you got me around to explain things?) Exercise: Modify the last exercise to throw up a prompt box asking for a number, then round it, then throw up an alert box with the rounded number. Here is a solution. Exercise: Combine the last two exercises to get the square root of a number then present it in rounded form. Then, and this is a little tough, determine if the number has in fact been rounded and

http://www.htmliseasy.com/javascript/lesson18.html[8/2/2011 3:32:05 PM]

Javascript Tutorial - Lesson 18

give a different message depending on whether it's rounded or not. Let me explain further. The square root of 9 rounded is 3. It's exactly 3. The square root of 10 is 3.3333... The square root of 10 rounded is around 3. So, I want you to alter the function so that if the user enters 9 it says...
The square root of 9 is exactly 3.

If the user enters 10 I want it to say...


The square root of 10 rounds to about 3.

You are going to have to do two things. One, find a way to determine if it rounds evenly or not. And two, you're going to have to stick an if-else statement in there to deal with the two possible outputs. Good luck and persevere until you figure it out. Here is a solution. There are other Math methods... Math.floor() rounds down. Math.floor(3.2) is 3. Math.floor(3.9) is 3. Math.ceil() rounds up. Math.ceil(3.2) is 4. Math.ceil(3.9) is 4. Math.round() by the way would round anything less than 3.5 to 3, and 3.5 or greater to 4. How to round to the nearest tenth? Quite simple really... multiply a number by 10, round it, then divide by 10. Try it. There is Math.sin(), Math.cos(), etc. There is Math.max(). (Hey, wasn't that a movie with Mel Gibson?) Math.max(x,y) returns the greater of two numbers while Math.min(x,y) returns the lesser. Math.max(2,8) returns 8 and Math.min(2,8) returns 2. There are a few others, and especially if you're a math person, I encourage you to study further.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

http://www.htmliseasy.com/javascript/lesson18.html[8/2/2011 3:32:05 PM]

Javascript Tutorial - Lesson 18


Practice exercises

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson18.html[8/2/2011 3:32:05 PM]

Javascript Tutorial - Lesson 19


You are here: Home Javascript Tutor Lesson 19

Javascript Tutor - Lesson 19


The for statement.
The for statement is a very useful tool. Here is an example...
<html> <head> <title></title> <script type="text/javascript"> function boxPopper() { for (var x = 0; x < 5; x++) { alert(x); } } </script> </head> <body> <a href="javascript:boxPopper()">Click here</a> </body> </html>

Try it. Here's what's happening in that for statement... 1. 2. 3.


for ( x = 0; x < 5; x++ ) for ( x = 0; x < 5; x++ )

-- x starts at 0

-- if x is less than 5, execute the instructions in the succeeding curly brackets once. If x is NOT less than 5, end the loop.
for ( x = 0; x < 5; x++ )

-- assuming x is less than 5, increment x by one and loop back to step

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 ;-) Exercise: Using the for statement, come up with a script that calculates the square root of each integer from 0 to 20, rounds each to one decimal point and displays them in an alert box like so...
The square root of 0 is 0 The square root of 1 is 1 The square root of 2 is 1.4 etc...

Hint: you can specify a line break in an alert box with an escaped n (n for newline) - \n

http://www.htmliseasy.com/javascript/lesson19.html[8/2/2011 3:32:18 PM]

Javascript Tutorial - Lesson 19 alert("Hand\nhand\nfingers\nthumb");

- try it

Again, it's a tough one. Hey, if they were easy you wouldn't learn anything, right? Here is a solution. Exercise: Make a slight alteration to that last exercise and have it round to two decimal places. Here is a solution.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson19.html[8/2/2011 3:32:18 PM]

Javascript Tutorial - Lesson 20


You are here: Home Javascript Tutor Lesson 20

Javascript Tutor - Lesson 20


Forms and javascript.
We've already done a little with forms. We're going to do a little more. Forms and javascript are like milk and cereal. Milk is good and cereal is good. But they're even better together ;-) Exercise: Just for the sake of refreshment, make a text box and a button. When the user clicks the button, whatever is in the text box gets thrown up in an alert box. Here is a solution. You know, now that I'm thinking about it, when you see these examples, and when you do your own scripting, you may find that there are different ways to do things. You can take a script and often condense it into fewer and more efficient instructions. Over time, you will certainly pick up a trick here and there to make your scripts leaner and more compact. You should know that the examples in this tutorial are deliberately scripted in a simple, loose, consistent and easy to understand manner. My job is to have you learn, not try to impress you with how confusing I can make things. If someone should tell you that there is another way to skin that cat, they're probably right. But rest assured, everything here is perfectly fine code, and more importantly, is written plainly enough to be understood by a beginner. Exercise: Make three more text boxes(inputs) a little further down the page. Alter the script so that when you click the button, the contents of box 1 move to box 2, the contents of box 2 move to box 3, the contents of box 3 move to box 4, the contents of box 4 go bye-bye, and box 1 is cleared. Hint: there is no "clear" method for text boxes... you can however set it's value to "". Here is a solution. Again, not the most useful script in the world. But look at it this way... think of how much javascript you understand compared to when you started these lessons. You've come a long way baby! A common type of form element is the radio button. Consider the following script...
<html> <head> <title></title> <script type="text/javascript"> function FruitBox() { alert(window.document.myform.fruit.value); } </script> </head> <body> <form name="myform">

http://www.htmliseasy.com/javascript/lesson20.html[8/2/2011 3:32:28 PM]

Javascript Tutorial - Lesson 20

<input type="radio" name="fruit" onClick="window.document.myform.fruit.value = 'oranges'">Oranges & Tangerines<br> <input type="radio" name="fruit" onClick="window.document.myform.fruit.value = 'bananas'">Bananas<br> <input type="radio" name="fruit" onClick="window.document.myform.fruit.value = 'peaches'">Peaches, Nectarines & Plums<br> Choose your favorite and <a href="javascript:FruitBox()">click here</a>. </form> </body> </html>

Try it. 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 if 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. Understand what's going on before you continue.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson20.html[8/2/2011 3:32:28 PM]

Javascript Tutorial - Lesson 21


You are here: Home Javascript Tutor Lesson 21

Javascript Tutor - Lesson 21


We can dynamically check and un-check radio buttons with javascript. The basic syntax is:
button.checked = true button.checked = false

(checks a radio button) (unchecks a radio button)

checked is a property of the radio button object. Have a look at this...


<html> <head> <title></title> <script type="text/javascript"> function FruitBox() { window.document.myform.fruit[0].checked = true; } </script> </head> <body> <form name="myform"> <input type="radio" name="fruit" onClick="window.document.myform.fruit.value = 'oranges'">Oranges & Tangerines<br> <input type="radio" name="fruit" onClick="window.document.myform.fruit.value = 'bananas'">Bananas<br> <input type="radio" name="fruit" onClick="window.document.myform.fruit.value = 'peaches'">Peaches, Nectarines & Plums<br> To select Oranges <a href="javascript:FruitBox()">click here</a>. </form> </body> </html>

Try it. See what's going on? The group of radio buttons is an array... fruit[0], fruit[1] and fruit[2], and can be referenced as such. The function basically says, check the first element in that group, which happens to be Oranges. Exercise: Slightly alter the script to check bananas when the link is clicked. Here is a solution. Exercise: rather than having the number (0, 1 or 2) hard coded into the function, send it a number from the link. Send it 2 for peaches. Here is a solution. Now we'll add two more links, one for each fruit...

http://www.htmliseasy.com/javascript/lesson21.html[8/2/2011 3:32:43 PM]

Javascript Tutorial - Lesson 21

To select Oranges click here. To select Bananas click here. To select Peaches click here. We'll also add a fourth line that grabs the current value and throws it up in an alert box... To read the current value click here. Here is what we have to this point...
<html> <head> <title></title> <script type="text/javascript"> function FruitBox(whichfruit) { window.document.myform.fruit[whichfruit].checked = true; } </script> </head> <body> <form name="myform"> <input type="radio" name="fruit" onClick="window.document.myform.fruit.value = 'oranges'">Oranges & Tangerines<br> <input type="radio" name="fruit" onClick="window.document.myform.fruit.value = 'bananas'">Bananas<br> <input type="radio" name="fruit" onClick="window.document.myform.fruit.value = 'peaches'">Peaches, Nectarines & Plums<br> <br> To select Oranges <a href="javascript:FruitBox(0)">click here</a>.<br> To select Bananas <a href="javascript:FruitBox(1)">click here</a>.<br> To select Peaches <a href="javascript:FruitBox(2)">click here</a>.<br> To read the current value <a href="javascript:alert(window.document.myform.fruit.value)">click here</a>. </form> </body> </html>

Try it. Play with the thing a bit. Do you notice a problem? We can select items easy enough using the links, but when we do, the value (as far as javascript is concerned) still comes back as undefined. Interesting.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

http://www.htmliseasy.com/javascript/lesson21.html[8/2/2011 3:32:43 PM]

Javascript Tutorial - Lesson 21


Frames Tutor ColorPicker Upload your page Practice exercises

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson21.html[8/2/2011 3:32:43 PM]

Javascript Tutorial - Lesson 22


You are here: Home Javascript Tutor Lesson 22

Javascript Tutor - 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 type="text/javascript"> function FruitBox(whichfruit, fruitname) { window.document.myform.fruit[whichfruit].checked = true; window.document.myform.fruit.value = fruitname; } </script> </head> <body> <form name="myform"> <input type="radio" name="fruit" onClick="window.document.myform.fruit.value = 'oranges'">Oranges & Tangerines<br> <input type="radio" name="fruit" onClick="window.document.myform.fruit.value = 'bananas'">Bananas<br> <input type="radio" name="fruit" onClick="window.document.myform.fruit.value = 'peaches'">Peaches, Nectarines & Plums<br> <br> To select Oranges <a href="javascript:FruitBox(0,'oranges')">click here</a>.<br> To select Bananas <a href="javascript:FruitBox(1,'bananas')">click here</a>.<br> To select Peaches <a href="javascript:FruitBox(2,'peaches')">click here</a>.<br> To read the current value <a href="javascript:alert(window.document.myform.fruit.value)">click here</a>. </form> </body> </html>

Try it. See how that works? Keep studying it until you do. Again, once you get past the most basic scripts, you'll find there are often several ways to accomplish 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>

http://www.htmliseasy.com/javascript/lesson22.html[8/2/2011 3:32:57 PM]

Javascript Tutorial - Lesson 22

<script type="text/javascript"> function DoSomething(item1,item2) { alert(item1 + item2) } </script> </head> <body> <a href="javascript:DoSomething(1,'roses')">Click here</a> </body> </html>

Try it. We send the function 2 quantities. The function then uses those quantities in it's execution. Exercise: Build a script with five links.... Sonny Tom Fredo Michael Connie 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. Build this script and figure out a way to solve the his/her problem. Here is a solution. Here is another solution. Like I said, there is always more than one way to get the job done. All right, let's get back to forms and javascript... Exercise: Make a form with four radio buttons. Label each of the buttons with the name of a color. When the user clicks a radio button, the background color of the page changes accordingly. Hint: although it's often tempting to place javascript commands right in the link, you may find that this can be a little limiting. Let's suppose you wanted to add something to the function. If all the commands are in the link, you'd have to change all the links everytime you wanted to alter the script. If all the links find a way to point to a function, all you have to do is play with the function. So, with that in mind, build it so that the function is what does the work. Here is a solution.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

http://www.htmliseasy.com/javascript/lesson22.html[8/2/2011 3:32:57 PM]

Javascript Tutorial - Lesson 22


QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson22.html[8/2/2011 3:32:57 PM]

Javascript Tutorial - Lesson 23


You are here: Home Javascript Tutor Lesson 23

Javascript Tutor - Lesson 23


Multiple functions.
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 type="text/javascript"> function SayHi() { GetName(); alert("Hello " + myname); } function GetName() { myname = prompt("What's your name?", ""); } </script> </head> <body> <a href="javascript:SayHi()">Click here</a> </body> </html>

Try it. See what's happening here? The link calls SayHi() which in turn calls GetName(). After GetName() executes, control goes back to SayHi() and the alert box pops up. Now, there's an important rule that you should know about... a variable declared within a function is only available in that function. A variable declared outside of any function is available anywhere (global variable). But, if you look at the function GetName(), you'll see the variable myname appears to be declared in a function, yet it is still available to the function SayHi(). How is that? Well, we didn't exactly "declare" myname... we just used it. Just using a variable makes it a global variable by default. It's then available to any function on the page. To actually declare a variable somewhere, you must preceed it with "var". To see the difference, alter the above example by declaring the variable myname within GetName()...
var myname = prompt("What's your name?", "");

Try it.
http://www.htmliseasy.com/javascript/lesson23.html[8/2/2011 3:33:08 PM]

Javascript Tutorial - Lesson 23

Kinda sorta don't work, right? So why did it work before? Because earlier, without an actual declaration using "var", the script just assumed it was a global variable... no matter where it was. In the preceeding example, we specifically declared the variable within the function, thereby causing it to no longer be a global variable. So, why is this important? Why not make ALL variables global? Well, when you get into larger scripts, you'd have to be very careful naming your variables. Actually, you CAN make all variables global. We've been doing it all along. We just have a choice now. You could use a variable named "name" in ten different functions without the script confusing them, or inadvertantly changing their values. All this talk about multiple functions and golobal vs local variables leads up to a very important concept... reusability. A reusable function is a function that performs a specific task, and is portable to many applications. You write a little snippet that does a certain something and whenever you need that certain something done, you just toss in the function and use it like a little tool. There's a little piece of reusable code that I reuse all the time. It's my random number generator...
// Random number generator. If max=3 then function returns 1,2 or 3 function getRandom(max) {return (Math.floor(Math.random()*max))+1;}

The function is condensed into one line for ease of use. I leave the comment above it as a reminder. Whenever I want a random number between 1 and something, I simply call getRandom(something). (Needless to say I place this snippet somewhere in the script) If I want a random number between (and including) 1 and 100 I call getRandom(100). 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 type="text/javascript"> // Random number generator. If max=3 then function returns 1,2 or 3 function getRandom(max) {return (Math.floor(Math.random()*max))+1;} function GetNumber() { mynumber = getRandom(10); alert(mynumber); } </script> </head> <body> <a href="javascript:GetNumber()">Click here</a> </body> </html>

Try it. mynumber equals what the function returns. The function returns a random number between 1 and 10, so mynumber equals a random number between 1 and 10. Actually you could condense the function...

http://www.htmliseasy.com/javascript/lesson23.html[8/2/2011 3:33:08 PM]

Javascript Tutorial - Lesson 23

function GetNumber() { alert(getRandom(10)); }

Understand this concept before you move on.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson23.html[8/2/2011 3:33:08 PM]

Javascript Tutorial - Lesson 24


You are here: Home Javascript Tutor Lesson 24

Javascript Tutor - Lesson 24


Exercise: 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."). Here is a solution. Exercise: Add a for statement to loop through the thing five times with every click of the link. Here is a solution. Exercise: Now, instead of looping five times, have it loop a random number of times (between 1 and 8). Before the loop starts, throw up an alert box stating "I will execute the loop X times.", X being the random number between 1 and 8, then execute the loop X times. Confusing? Probably, but hey, we're way beyond Hello World and I did warn you that things could get rough. Besides, if you've made it this far, and you at least have half a clue what you're doing, then I'd say you're doing just fine! Keep plugging away! Here is a solution. Exercise: Alter your last exercise to loop a random number of times between 4 and 9 rather than 1 and 8. Do not alter the random number generator. Use getRandom() exactly as-is for both tasks. Here is a solution. This is an example of creative problem solving. I've told you that programming is an 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; }

http://www.htmliseasy.com/javascript/lesson24.html[8/2/2011 3:33:26 PM]

Javascript Tutorial - Lesson 24

Or even more simply...


function myAverager(num1,num2,num3) { return ( (num1*1) + (num2*1) + (num3*1) ) / 3; }

Exercise: Using the myAverager() function above without any changes, create a script with three text input boxes and a button. When the button is pressed, an alert box is thrown up that says something like...
The average of 10, 22 and 13 is 15.

Your solution should be to grab the three values, send them to myAverager() and pop up an alert box with the answer. Here is a solution. Exercise: Make your last exercise round the answer to two decimal places. Here is a solution.

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

NEXT >>

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson24.html[8/2/2011 3:33:26 PM]

Javascript Tutorial - Lesson 25


You are here: Home Javascript Tutor Lesson 25

Javascript Tutor - Lesson 25 - Last one!


Well, that about wraps up this tutorial. Or rather, even though there are still a couple hundred more topics to cover and a thousand more exercises to do, this is where I'm going to stop. We've gone from nothing to a reasonably solid grasp of basic javascript programming... and that was the goal. We've covered a dozen topics and you did about 50 exercises (I hope). You now have your foot in the proverbial door. I encourage you to expand your knowledge by creating new scripts. Build on what you've learned. Utilize fully the resources at your disposal. Your knowledge and skill will increase in direct proportion to how much scripting you do.

JavaScript resources and references:


JavaScript Authoring Guide Included with this tutorial is Netscape's JavaScript 1.1 documentation. I find this the most useful and easiest to understand javascript reference available. Hopefully you will find it useful as well. JavaScript FAQ at 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 probably find it there. Google Groups (Advanced Search) Google Groups is the latest and greatest archiver of all newsgroup discussions. Anything anyone has ever posted on any one of 30,000+ newsgroups is stored there and the search facilities are plenty strong. There happens to be a newsgroup called comp.lang.javascript where javascript related issues are discussed on a daily basis. Past discussions are searchable and are an incredible wealth of information. Javascript Kit - Complete JavaScript Reference A very nicely done javascript reference. Well organized, simple, useful. MSDN (Microsoft Developer Network) JScript documentation Microsoft's documentation. The MSDN website is very extensive and contains a massive amount of very useful information. Unfortunately, there are a few drawbacks. Navigating it is a little confusing... sort of like swimming through mud. It's got a Microsoft slant to it and the site seems to work best using Internet Explorer. Still, I recommend using it as a reference not only for javascript, but for other web development topics as well. If you would like to add a link to HTMLisEasy.com, you are welcome to. You may link as you wish

http://www.htmliseasy.com/javascript/lesson25.html[8/2/2011 3:38:16 PM]

Javascript Tutorial - Lesson 25

or use of these groovy text links. Just copy and paste the desired code into your page...
HTMLisEasy.com <a href="http://www.htmliseasy.com" style="text-decoration:none;"><span style="font:bold 11px arial;"><span style="color:#40A840;">HTML</span><span style="color:#748874;">is</span><span style="color:#40A840;">Easy</span><span style="color:#125598;">.com</span></span></a>

HTMLisEasy.com
<a href="http://www.htmliseasy.com" style="text-decoration:none;"><span style="font:bold 14px arial;"><span style="color:#40A840;">HTML</span><span style="color:#748874;">is</span><span style="color:#40A840;">Easy</span><span style="color:#125598;">.com</span></span></a>

HTMLisEasy.com
<a href="http://www.htmliseasy.com" style="text-decoration:none;"><span style="font:bold 18px arial;"><span style="color:#40A840;">HTML</span><span style="color:#748874;">is</span><span style="color:#40A840;">Easy</span><span style="color:#125598;">.com</span></span></a>

Or, the following code will just add the colors and bold, so the font matches your page font...

HTMLisEasy.com
<a href="http://www.htmliseasy.com" style="text-decoration:none;"><b><span style="color:#40A840;">HTML</span><span style="color:#748874;">is</span><span style="color:#40A840;">Easy</span><span style="color:#125598;">.com</span></b></a>

Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide JavaScript FAQ HTML 4.0 Reference Google Groups (Advanced Search)

<< BACK

QUICK SITE GUIDE HOME SITE MAP - a detailed listing of EVERYTHING here. CONTACT DOWNLOADS Basic HTML Tutor Table Tutor Form Tutor Frames Tutor ColorPicker Upload your page Practice exercises Barebones HTML Guide Javascript Tutor - A solid beginner's javascript course Email Scrambler - Fight Spam! CSS/Stylesheet Tutor - Basic Style Sheets 101 Meta Tag Tutor - Learn about META tags and effective search engine ranking strategies GateKeeper - cool password protection with javascript that anyone can use Magic Buttons - learn to make javascript mouseovers Web Resources - a listing of quality resources useful to any web author... graphics, javascripts, cgi, etc. How to keep an idiot busy

"If you build it, they will come."

http://www.htmliseasy.com/javascript/lesson25.html[8/2/2011 3:38:16 PM]

You might also like