Академический Документы
Профессиональный Документы
Культура Документы
by Jeremy Wray
Contents
• Introduction • Loops
• JavaScript tag ○ While Loops
• Alert Boxes Another While Loop
• JavaScript Comments ○ For Loops
• Multiple Alerts Nested For Loop
• Variables Another For Loop (homework)
○ Outputting variables • Arrays
• Strings/prompt() Method ○ Arrays & Loops
○ String Methods ○ Arrays in the DOM
• If / Then Branching • Functions
○ If / Then Conditions ○ Parameters & Return Values
○ Combining If / Then ○ Functions With More Than 1 Parameter
Conditions
• JavaScript & Forms
• If / Then / Else
○ Another form example
• Events and Event Handlers
○ Text Field Events
• Image Swapping
○ Text Field Methods
○ Image Pre-Load
○ Form Handlers
○ More Complex Image
Swapping ○ Form Validation
• The Document Object Model ○ Checkboxes
(DOM) More Checkboxes
○ Object Properties ○ Radio Buttons
○ Object Methods More Radio Buttons
• Communicating Between ○ Selects
Windows selectedIndex
• Window Manipulation in selected Property
JavaScript
○ Form Summary
• Frame Hierarchies
• eval
○ More Frame Hierarchies
○ Another Frame Demo
Introduction (top)
The purpose of this tutorial is to provide an introduction to the JavaScript programming
language. It assumes no knowledge of programming, however it requires a good knowledge of
HTML since the primary use of JavaScript is to be imbedded within an HTML document and to
be interpreted within a web browser. Other good sources for study include the brilliant
Webmonkey site, and the book "JavaScript: The Definitive Guide (4th Edition)" by David
Flanagan and published by O'Reilly.
The form of this tutorial is basically lots of little examples of script with explanations of their
use. Most of the headings at the top of each section are also links to a page demonstrating the
topic. Play with them, alter them and learn! All of the examples can be used since they download
into your browser when opened. In Internet Explorer, use the View menu and choose Source to
see the code, if using Navigator, save the file, then open it in Notepad or similar text editor, or
you can download the whole tutorial in Zip format (see below) to save your net connection.
Where JavaScript code is written within the text of the tutorial, it appears in this colour and font
to distinguish it. HTML code is written in this colour and font. Bits of code which are not the
focus of attention are lowlighted like this.
Just before we go on, JavaScript IS NOT the same as JAVA, the language developed by Sun
Microsystems. It was called JavaScript as a marketing ploy, it was originally called LiveScript.
The two languages can, however, be used together, but I don't cover this here.
If you wish to contact me, about errors, omissions, praise, criticism or just for a laugh, mail me
on: jel@jelnet.co.uk
</script >
Notice the "--end of HTML comment-->" preceeded by the "//", this is done since otherwise
JavaScript will read the closing HTML comment as an error. The browser will not display
anything anything between html comment tags (i.e. script statements), however if it's JavaScript
enabled it will process those statements.
Variables (top)
Statements are the sentences of Javascript, semi-colons are the end punctuation marks, spaces
and line-breaks are ignored. The semi-colons are sometimes missed out, but should be used or
they can mess up code later on.
Variables are a way of storing information in Javascript. There are written like this, usually in the
header part of the web page:
var secs_per_min = 60;
The var part is not strictly necessary but useful as it tells us that what follows is a variable. They
must start with either a letter or an underscore, after that, they can have numbers. In some
browsers they are case sensitive, some not, but it's best to chose a naming convention and stick
with it, for example the above variable could also be written:
var SecsPerMin = 60;
They should try to be descriptive (for later/other people's recognition) but not too long to type.
You don't have to give the variable a value right away, for example you can define a variable
with an empty value, which is going to be used later like this:
var MyVariableForLater = "";
This is a good practice to prevent errors, particularly when a variable may or may not be used in
a later part of the program. Variables can be made of a sum of others. For example, if we create
two variable like this:
var secs_per_min = 60;
var min_per_hour = 60;
We could create:
var secs_per hour = secs_per_min * min_per_hour;
The "*" operator here means "multiply".
so as to make copies of the both text string in different styles, eg. bold or italic:
var bold_both = both.bold();
var italic_both = both.italics();
var upper_both = both.toUpperCase();
var red_font_both = bold_both.fontcolor('red');
These styles, eg. toUpperCase() are actually methods of the JavaScript String object of which
there are quite few. Notice the above style changes could also be written with HTML, eg. The
italic style could be written as:
var italic_both = "<i>" + both + "</i>";
The document.writeln() method is then used to write the results to the page:
document.writeln(both + "<br>");
document.writeln(italic_both + "<br>");
document.writeln(upper_both + "<br>");
document.writeln(red_font_both + "<br>");
Finally, you may have noticed that previously I said that a method was a function attached to an
object, however, when I used the prompt() method, above, it was not attached to anything. Well,
in fact it was, it was attached to the window object and it could have been written as:
window.prompt(), it's just that window is the default object and it's presence is assumed in the
absence of anything else and so doesn't have to be written. Among the many window object
methods is also alert().
if (question == "yes"){
alert ("Great! Here's the results, please read on!");
}
Note the "= =" in the condition, this simply means "equals". A common mistake is to use a single
"=" which would have the effect of saying that question should equal "yes".
in this example (remember Strings/Prompt Method, above), bold() is a method of the object both
which itself is a String Object. A string object is created when you assign a string to a variable.
In JavaScript, strings are objects themselves, so bold() is a method of the String object. The main
difference with methods is that they are followed by parenthesis (), that sometimes contain the
parameters of the method. Note that they are accessed in the same way as properties, with the
object, dot, then the method. The parenthesis must be there even if they contain nothing.
We've already seen examples of the alert and prompt method. These in fact are methods of the
window object and could have been written as:
window.alert ("This is an alert");
However, because window is the default top-level object, it can be left out as in our alert() and
prompt() examples above. Another two methods of the window object are focus() and blur(), one
brings a window to the front, the other pushes a window behind. However, in order to see it work
we need a couple of smaller windows and to "invoke method calls" on other windows...
window.open('newpage.htm','window_name','location,menubar')
Gives a window with just the location box and menu bar.
window.open('newpage.htm','window_name2','location,width=500,height=200')
Gives a window that is a 500 pixels by 200 pixels with just the location window.
window.open('newpage.htm','window_name3','location,width=500,height=200,scrollbars,resizab
le');
Gives a window the same as above one except it is resizable and has scrollbars.
window.open('newpage.htm','window_name4','status')
Shows just the Status Bar.
window.open('newpage.htm','window_name5','toolbar,directories')
Shows Toolbar and Directory Buttons (Netscape).
Loops (top)
Loops are used to do similar things more than once. They perform tasks over and over, usually
for a certain time limit or until a certain condition is met. They are an extremely powerful aspect
of programming and a good grasp of them is essential for any programmer. They may well look
baffling at first, but don't worry, they can be very confusing at first, but persevere, because they
will start to make sense. We'll cover the main aspects of loops here, and start with an easy one...
While Loops (top)
The while loop keeps doing something "while" a certain condition is met, they written in this
form:
while (some condition is true) {
execute these statements;
}
In the linked example, a password is requested before executing the rest of the page. It's coded
like this:
//create variable
var answer = "";
This says that the the_x_string is equal to itself plus an "x", so each time the loop runs the string
of x's grows by 1.
counter = counter + 1;
This increments the counter by one each time the loop runs. This will continue until counter is is
equal to number_x at which time the_x_string will have as many "x"'s as the user entered and the
loop condition will no longer be true (ie. counter is no longer less than number_x), causing the
loop to immediately exit and the next piece of code to run:
alert (the_x_string); Which brings up an alert diplaying the the_x_string.
Now I'll show you a couple of handy programmer's shortcuts to make the above code a bit
shorter. Firstly, we could have written this line: the_x_string = the_x_string + "x"; like this:
the_x_string += "x";
This make use of the += operator which says "add something to myself", in this case, an x. This
operator also be used with numbers ie. if you have a variable a_number = 3; and you do
a_number += 2;, a_number would become 5.
Next, we could have written this line: counter = counter + 1; like this:
counter ++;
This shortcut makes use of the ++ operator which says "add one to myself". Of course we could
also have written it as: counter += 1;. All of these different ways of doing things may seem a bit
confusing, and I showed you the long way first so these short methods were easier to understand.
As with many aspects of computing (and life!), there are many ways of achieving the same thing.
However, don't get too hung up on writing the most efficient code, the important thing is that
your program does what you want, and is easy for you and others to understand at a later date.
Leave the optimisation to later.
Functions (top)
Functions, or subroutines, as they're sometimes called, are bits of JavaScript that you can call
over and over without having to rewrite them every time. They come in this format:
function functionName (parameter list) {
statements ...;
}
Note the keyword function, followed by the function name. The naming conventions are the
same as for variables, the first character must be an underscore or letter. You must not name a
function the same as a variable or there'll be strange results, therefore it can be useful to use a
different naming convention such as internal capitalisation (internalCapitalisation) for functions
and underscores (variable_name) for variables, to avoid clashes.
After the function name, come the brackets ( ) which can contain parameters, which are
additional values that can be passed into the function, but these we'll come onto that later, but
note that even if the function has no parameters, those brackets must still be there. Then there's
the code statements, contained within curly { } brackets. You can then call your function, ie. get
it to run, like this:
functionName (parameter values);
OK, enough theory, lets go through the example above, line by line, first we name the function,
announceTime(), notice it has nothing between the brackets which means it has no parameters:
function announceTime() {
Next comes the body of the function between the {}'s. This is what is run each time the function
is called. First a variable the_date is created to reference a new Date() object. This is one of the
handy built-in JavaScript objects, which when created, is automatically set to the current date
and time from the user's computer:
var the_date = new Date();
The new Date() object returns a string of the current date and time, however if you want to be
more specific and get say, just the minutes, or seconds, you have to call other methods on it. So
the next lines call these built-in methods getHours(), getMinutes() and getSeconds()on the new
Date():
Notice the square brackets [] after each array name referring to the index in the array, that being
the value of the current loop (loop_1) and (loop_2) respectively. Once the common fish is found,
it's name is taken from the first array and loop common_elements += array_1[loop_1] however,
it could have just as well have been taken from the second array and loop as that is referring to
the same fish, eg. common_elements += array_2[loop_2]. You may be wondering what the +", ";
at the end of the middle line, above. That's to add a comma and space after each fish.
Once it's gone through the sea fish (array_2), it exits the loop and moves onto the next small fish
in the enclosing loop and repeats the process until it's gone through all the fishes in array_1. So
now, the common_elements variable should contain all fishes common to both arrays.
Now comes the time to display the common elements (fishes) from the arrays. Now it's
important to remember that the function commonArrays simply compares arrays and displays the
items which are common. It does not know, or care, whether the arrays contain cars, trees or
whatever. So, the function has another handy little parameter called common_name. This is
simply a way of passing in a text label for our results:
alert (common_name + " are:" + common_elements);
In this case common_name is the text "Small Sea Fishes". Finally let's look at where the function
is called from the hyperlink in the page:
<a href="#" onClick="commonArrays('Small Sea Fishes', small_fishes, sea_fishes);">Which are
Sea Fishes that are Small ?</a>
The function is called from an onClick event handler. Notice after the function name
commonArrays, there are the three parameters in brackets, separated by a comma. So 'Small Sea
Fishes' becomes common_name (which is used in the alert), when it's passed to the function,
notice it's a text-string. Then small_fishes refers to the array defined above and so doesn't need to
be in quotes, this becomes array_1 in the function. Finally sea_fishes is passed in and becomes
array_2. Note that the number of items defined when the function is called must be equal to the
number of parameters in the function, otherwise there will be erroneous results.
Bottom of Form
Bottom of Form
Bottom of Form
Hover to Focus - uses focus() method to place cursor in the text field.
Hover to Blur - uses blur() method to remove cursor from text field.
Hover to Select - uses select() method to select contents of text field (may not work in
Navigator).
Here is the html to create the form:
<form name="method_form">
<input type="text" name="method_text" size="20" value="Watch This Space">
<input type="reset" value="reset">
</form>
And here is the code in the links:
<a href="#" onMouseOver="document.method_form.method_text.focus();">Hover to Focus</a>
<a href="#" onMouseOver="document.method_form.method_text.blur();">Hover to Blur</a>
<a href="#" onMouseOver="document.method_form.method_text.select();">Hover to
Select</a>
Calling methods on a text field is just like accessing the methods of any object:
object_name.method_name(). The name of the form above is method_form. The name of the text
field above is method_text. So, to call the focus() method on the text field above, we call:
document.method_form.method_text.focus();
Un-Handled Button
Bottom of Form
You should have seen that the page got reloaded, which was a pain as you would have been right
at the top again. Now try this one:
Top of Form
Handled Button
Bottom of Form
This one should not have done anything due to the onSubmit in the form tag looking like this:
<form onSubmit="return false;">
Generally, return false is a way of stopping your browser doing what it would normally do. It can
also be used in the onClick part of a link, eg. <a href="file.htm" onClick="return false;">
Link</a>. This link should do nothing.
else{
return true;
}
}
And there ends the function.
Checkboxes (top)
Checkboxes are used in forms to choose multiple items, a bit like multiple selects. They consist
of a name/value pair, and when the item is checked, that name/value gets submitted with the
form. Here's an example:
Top of Form
Eggs Cheese
Bottom of Form
if(document.checkform.checkbox.checked == true){
alert('Yup, it is checked!');
}
else{
alert('Nope, it is not checked.');
}
}
So a different alert is displayed depending on whether the checked property of the checkbox is
true or not.
Yes No
Bottom of Form
Selects (top)
Selects are usually used to select one item from a list, or multiple items using Ctrl+click if the
multiple keyword is used in the select tag. In the example, the select in the form is a single select
and coded like this:
<form name="select_form">
<select name="foods" size="4">
<option value="10">Bread</option>
<option value="20">Eggs</option>
<option value="30">Cheese</option>
<option value="40">Fish</option>
<option value="50">Milk</option>
<option value="60">Bananas</option>
</select>
</form>
All the options in selects, like radio buttons, are formed into an array by the JavaScript DOM.
Their values are accessed like this:
document.form_name.select_name[array_index].value
However, select options not only contain values, but also text strings. For example, the value of
the Bread option, above, is 10, but it's text is "Bread". Let's look in detail at the links in the
example:
<a href="javascript:alert(document.select_form.foods[2].value);">What's the value of Cheese?
</a>
Here we're trying to get the value of cheese. Cheese is index [2] in the foods array, so we
reference that and get it's value, which is 30.
selectedIndex (top)
So far we've accessed text and values of select options using their index in the options array.
However, often you want to know which option a user has selected. For this, there is the handy
selectedIndex property of the options array. It's value can be accessed like this:
document.form_name.select_name.selectedIndex
This property returns the index number in the array of the selected option. If nothing is selected,
it returns -1. The example uses the same form code as the previous example. Let's look at the
links in the example:
<a href="javascript:alert(document.select_form.foods.selectedIndex);">What's the
selectedIndex?</a>
This link returns a number, for example if "Bread" is selected it returns 0. If nothing is selected,
it returns -1. Once we've ascertained the selectedIndex, we can use it to query the text and/or
value of the selected option, that's what we're going to do on the next links:
<a href="javascript:getSelectedValue();">What's the value of the selectedIndex?</a>
This link calls a function to get the selected value. It's easier this way as there's a few lines of
code to get the value, here's the function:
function getSelectedValue(){
Form Summary
Here's a quick summary of the stuff we've covered in JavaScript and Forms:
• Form elements can be referred to like this: document.form_name.element_name.
• Text field and textarea form inputs have value properties which can be referred to and set
using: document.form_name.element_name.value.
• Text field and TextArea form elements understand: onFocus(), onBlur() and onChange()
event handlers.
• Forms have an onSubmit() event handler triggered when the form is submitted or the
Return keyis hit in a form field. Use return false to stop a form submitting if you don't
want it to.
• Checkboxes and radio buttons have a checked property. You can read and write this
property which returns either true or false.
• Checkboxes and radio buttons have an onClick event handler Just like links, you can use
this to trigger functions when a user clicks on a checkbox or radio button.
• Selects have an array of their options. Just like any array, you can find the length of the
options array by using document.form_name.select_name.length.
• You can change the text of an option by messing with its text property. To change the
text of the first element of a select you'd type
document.form_name.select_name[0].text='new text'; .
• You can find out which option was selected using the selectedIndex property of the select
element, document.form_name.select_name.selectedIndex returns the array index, you
can then use document.form_name.select_name[array_index].text to find out what was
actually selected.
eval (top)
eval() is a very useful JavaScript method. It is basically used to "evaluate" whatever is passed to
it. In our example, I used a function to add 7 to a form field. If we started with 2 and added 7,
without eval(), we would end up with 27, which is literally 2, with seven plonked next to it.
That's because even though a number was entered in the form, JavaScript sees that as a text
string, and when the + operator is used with strings, it concatenates (joins) them. Using eval(),
evaluates the contents of the field and turns it into a number instead of a string, eg. 2 becomes
the value 2 rather than the character 2, therefore when we add 7 to it, we get 9. Here's how the
example "Adding a number WITH eval()" works:
function evalFunction() {
var the_value = eval(document.evaluate.number.value);
In the first line of the function we pass the value of the input field number from the form called
evaluate to eval()and make it the variable the_value. Thats means that the_value equals the
numeric value of a number character the user entered.
document.evaluate.number.value = the_value += 7;
This line updates the same form field after adding 7 to it. The function used in the example
"Adding a number WITHOUT eval()", is exactly the same, except that the field value is not
passed to eval().
eval() can also be used to evaluate a text string and evaluate it into a variable, if one exists. In the
example, "Entering a variable name WITH eval()", typing the words "cats", "cars" or "trees" into
the field and hitting "Process" produces a list of those items. This is because some variables were
set in the header of the document like this:
var trees = 'Fir, Oak, Birch, Maple, Ash';
var cats = 'Tabby, Siamese, Tiger, Lion';
var cars = 'Mini, Golf, Mercedes, BMW';
Then, the function goes like this:
function evalFunction2() {
var the_word = eval(document.evaluate3.word.value);
document.evaluate3.word.value = the_word;
}
The function is similar to the one above except that eval() evaluates what the user typed in eg.
"cats" and determines that there is a variable of the same name in the document. Thus the
variable the_word becomes equal to the variable cats instead of the text string the user enetered.
That variable then updates the same field with it's content, ie. a string containing a list of cats.
Again, the example "Entering a variable name WITHOUT eval()", is exactly the same function,
but without sending the field entry to eval(), and this simply re-updates the field with the same
string, so nothing appears to happen.
Anyway, that's the tutorial over for now. I hope to have a more advanced tutorial up soon, that's
not to say we haven't covered some quite advanced topics here, but it would be nice to delve
deeper into some of these topics and explore new ones. I don't know when it will be up, but no
doubt if you email me and say you want it, it will encourage me to do it sooner rather than later!
OK, thanks for reading this far...see you soon!!!
(top)