Javascript Tutor
Javascript Tutor
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>
<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>
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
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
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()
{ 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
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>
<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
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
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>
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. 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!"); }
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
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.", "");
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...
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...
12 12 12 12
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 >>
(Right this moment the value is nothing, but nothing is still a value.)
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>
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.
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
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.
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
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]
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
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
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
== 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;
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()">
=
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
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;
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]
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
<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>
</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")">
<< 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
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
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>
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
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.
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();
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 >>
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
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
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.
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.
and the
/************************************************* - This is all comments here. - You can write all kinds of stuff in a comment like this. **************************************************/
// Comment //
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>
<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.
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 >>
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
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.
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>");
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.
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
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
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.
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
-- 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++ )
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
- 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
<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
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...
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
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>
<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 >>
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]
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...
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
(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; }
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
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