JavaScript is sometimes referred to as a programming language, but

advertisement
INTRODUCTION TO JAVASCRIPT
PROGRAMMING AND SCRIPTING LANGUAGES
JavaScript is sometimes referred to as a programming language, but it is really more accurate to call it a
scripting language. The difference between the two is subtle. In both types of languages, the source
code must be converted to machine language in order for the program to run. In programming
languages, the process is performed by a piece of software called a compiler and is completed before
the program runs. Once the compilation is completed, the program can be run without opening it within
another program. In scripting languages, the source code is processed by the target program, which for
HTML is the Web browser. When the document contains embedded JavaScript code, that code is
interpreted by the browser and converted to machine language one line at a time that occurs
automatically at run time, in a process called interpretation. The Web browser acts as interpreter
software.
THE POWER OF JAVASCRIPT IN WEBPAGES
Under normal conditions, the output of a JavaScript function will be nothing more than one or perhaps
several strings of text that are inserted into the host Web page. The resulting HTML page is then
processed by the browser just as it would be if it had been keyed into the source document. The real
power of embedding JavaScript code into a Web page comes from the fact that the resulting text can
change from one day to the next, or even from one minute to the next. It is entirely possible for one
person to enter a particular URL into his Web browser and see a Web page that is completely different
from the page that is seen by another person who enters the exact same URL. These different Web
pages could be the result of differences in time, location, or Web browsers. JavaScript is capable of
detecting various conditions in the current operating environment, reacting accordingly.
JAVASCRIPT PROCESSING
In order for the Web browser to detect if a particular HTML page contains embedded JavaScript, the
<script></script> tags are required. The Web browser interprets everything between these two tags as
JavaScript source code instead of the standard HTML text. The browser will then convert the script
(interpretation process) into binary code. This code will be executed and its output (if any) will be
inserted into the HTML text stream and displayed as if it had been typed into the original HTML
document. After the browser has finished processing the HTML document, the end result is that the
script tags and everything in between will be stripped out of the page and replaced by whatever the
output (result) is from the interpretation of the JavaScript. Also, any HTML formatting tags you put before
or after the script tags will be processed just as they would be in a page without any embedded
JavaScript code.
JAVASCRIPT SYNTAX
You need to understand that the scripts embedded between the script tags must conform to certain rules
of grammar, called program syntax. JavaScript is made up of keywords, operators, and objects with
properties and methods. Keywords are recognized as part of the language definition, are reserved by
the language and cannot be used as a variable. The primary purpose of JavaScript is to generate text
that will be inserted into the standard HTML text stream and contains a number of invisible entities call
objects with well-defined sets of capabilities, which are accessed through methods (functions) within the
objects. The programmer invokes the services of methods by keying the name of the object, followed by
a period (“dot”, also known as the dot operator), and followed by the method name. Methods are
followed by a parameter list enclosed in parentheses (sometimes the parentheses are empty). The
parameter list provides the method with the information it needs to perform its function correctly. Each
JavaScript statement is followed by a semicolon (;). Here is an example the syntax of an object, method,
and parameter list:
document.write(“A string of text.”);
1
INTRODUCTION TO JAVASCRIPT
HTML WITHIN JAVASCRIPTS
Since the code between the script tags must conform to strict syntax, you cannot simply use HTML tags
between the script tags. If you do this, the browser will not know how to interpret the code and give an
error message. If it is necessary to use HTML tags inside a script, you must enclose the HTML tags in
double quotes (“ ”), making it part of the output text stream. An example of this is:
document.write("<b><i>Good Morning</i></b><br />
<font color=’red’>Welcome To My Website!</font>");
CONDITIONAL STATEMENTS
One of the most powerful features of the JavaScript language is the conditional statement. This ability to
make decisions is common among all programming languages and gives programmers the ability to
evaluate a specific condition and then perform different actions depending on the results of that
evaluation. Just like JavaScript objects contain special functions called methods that perform various
tasks, they can also contain properties that programmers can access to obtain information about the
objects. The property of an object can be evaluated (used as part of the condition) to make decisions.
The syntax for accessing a property is the object name, then a dot operator, followed by the property
name. One of the properties that can be accessed is the appName property of the navigator object.
This allows the program to determine the name of the Web browser currently being used. Example:
navigator.appName
The syntax of the conditional statement in JavaScript is very important. It begins with the keyword ‘if’,
and then a condition is specified within a pair of parentheses. The condition is followed by a statement
block that consists of an opening brace ({), one or more JavaScript statements, and then a closing brace
(}). The opening brace indicates the beginning of a statement block and the closing brace marks the end
of that block. It is necessary to carefully code these braces, because if the number of opening braces
does not match the number of closing braces, it can cause serious problems in the program and will
result in syntax errors. Note the placement of the braces in the following syntax shell of a JavaScript
conditional statement:
if (<condition>)
{
statement i1;
statement i2;
statement i3;
.
.
.
statement iN;
}
else
{
statement e1;
statement e2;
statement e3;
.
.
.
statement eN;
}
2
INTRODUCTION TO JAVASCRIPT
The ‘else’ clause is optional, and defines the action to take if the specified condition is not true. The
‘else’ keyword appears immediately after the statement of the ‘if’ clause, and it is accompanied by a
statement block of its own. Some rules for avoiding problems with braces are:
1. Always place the opening brace directly below the keyword to which is belongs.
2. Always indent the statements contained within the statement block.
3. Always place the closing brace so that it is vertically aligned with its corresponding opening
brace.
The condition part of the syntax (<condition>) in JavaScript will always consist of two tokens separated
by a relational operator. A token can either be a variable name or a literal constant. The relational
operator can be any of the following symbols:
OPERATOR
MEANING
==
is equal to
!=
is not equal to
<
is less than
>
is greater than
<=
is less than or equal to
>=
is greater than or equal to
By using an object property in the condition with a relational operator and a literal, you can create a
conditional statement to evaluate whether a particular property meets a certain condition. For example:
if (navigator.appName==”Netscape”)
{
document.write(“You are using Netscape Navigator”);
}
else
{
document.write(“You are not using Netscape Navigator”);
}
Once a condition has been evaluated, either the ‘if’ statement block or the ‘else’ statement block will be
executed, but not both. If the result of the condition is true, the ‘if’ statement block will be executed and if
it is false, the ‘else’ statement block will be executed.
COMMUNICATING WITH THE USER IN JAVASCRIPT
The most common way to communicate with user in JavaScript is to use the document.write() method.
Another method to get the user’s attention is to use the alert() method. Its purpose is to display a special
dialog box to alert the user that an expected event has occurred or some kind of user input is required. It
is normally used when the user needs to be made aware of some unexpected error condition that has
occurred. It can also be used when the program needs some kind of user acknowledgement before
proceeding. This method is part of the interpreter itself and interacts directly with the underlying
operating system. For this reason, it is not necessary to include the object name and dot operator.
Example:
alert(“Netscape Navigator detected”);
Another way of providing information to the user is through accessing the browser status line via a
JavaScript program. A message displayed in the status line is a string value stored in the status property
of the window object. You can change this information in the status line within a JavaScript program by
the including the statement:
3
INTRODUCTION TO JAVASCRIPT
window.status=“Place your message here”;
So now you have three different ways to communicate with the user. If you put them altogether, you
could display a message to the user on the webpage itself, display a message in an alert dialog box, and
display a message in the status line. Example:
if (navigator.appName==”Netscape”)
{
document.write(“You are using Netscape Navigator”);
alert(“Netscape Navigator detected”);
window.status=“Netscape Navigator detected”;
}
else
{
document.write(“You are not using Netscape Navigator”);
alert(“Netscape Navigator required”);
window.status=“Netscape Navigator required”;
}
The status line can be used to let the user know what the program is doing. For example, whenever your
script is about to initiate a potentially lengthy process, such as downloading a large graphic image, it is a
good idea to display an appropriate message in the status line. This would notify the user that the
program is still working and has not crashed.
DYNAMICS GRAPHICS USING JAVASCRIPT EVENTS AND FUNCTIONS
JavaScript gives you additional capabilities beyond HTML when working with images to make graphics
“come alive”. In order to do this, you need to understand to have an understanding of JavaScript events
and functions.
JAVASCRIPT EVENTS
An event is a system-level response to the occurrence of some specific condition. Conditions can be
generated by the Web browser itself, but most are caused by the user performing some action, like
moving the mouse, clicking a button, or selecting text. Once a particular event is generated, JavaScript
gives you the ability to create Web pages that react to the event. The following table lists the types of
events you can use in JavaScript:
Event Name
onAbort
onBlur
onChange
onClick
onError
onFocus
onLoad
onMouseOver
onMouseOut
onSelect
onSubmit
onUnload
Event Trigger
The user aborted the loading of a Web page
The user deactivated an object (the object lost focus)
The user changed the object in some way
The user clicked the mouse on an object
The JavaScript interpreter encountered a script error
The user activated an object (the object received focus)
The Web browser finished loading a page
The mouse pointer passed over an object
The mouse pointer moved off an object
The user selected (highlighted) the contents of an object
The user submitted an HTML form
The Web browser unloaded a page from memory
4
INTRODUCTION TO JAVASCRIPT
JAVASCRIPT FUNCTIONS
A function is a segment of JavaScript code that can be invoked or called just like the document.write()
and alert() methods. The difference is that a method has already been defined as part of the JavaScript
programming language, whereas a function is written by the programmer and may contain any number of
JavaScript statements, including calls to JavaScript methods or other functions.
IMAGE ROLLOVERS
It is possible to make a graphical hyperlink respond to mouse movements in JavaScript. You can
change the appearance of an image when the user moves the mouse pointer over it, which is called an
image rollover. In order to accomplish this, you must use the JavaScript events called onMouseOver
and onMouseOut. The onMouseOver event occurs when the user moves the mouse pointer over a
particular object. The onMouseOut event occurs when the user moves the mouse pointer off of the
object.
To create the rollover effect, you will need two graphic images, which should be of the same size. In the
sample code, you will use a red arrow image and a blue arrow image, which differ only in their color.
What the effect does is ‘swap’ out images depending which mouse event is triggered. For this effect, you
will need to put the script tags in the header section of your HTML code. This will allow the Web browser
to process the JavaScript code before it begins to display the contents of the document on the screen.
For the rollover effect, it will allow the browser to load both images into memory before it displays the
body of the Web page. If we fail toe do this, the browser would not know what images it is to load when
the onMouseOver and onMouseOut events occur, resulting in a JavaScript error message.
JAVASCRIPT VARIABLES
You will also need to declare some variables in JavaScript for this rollover effect to work. A variable is a
name that is assigned to a literal value or to an object. Once this assignment is made, the name can be
used throughout the HTML document to refer to that particular value or object. To declare a variable in
JavaScript, you use the keyword ‘var’, followed by the name of the variable, and then declare the data
type for the variable. For the rollover effect, the type of variable we will declare is an image. Example:
var blueArrow = new Image;
The ‘new Image’ portion of the above statement is executing a special method called a constructor. It is
‘constructing’ (creating) a new image object and saving a reference to that object in a variable we are
naming ‘blueArrow’. You will also need to declare another variable for the red arrow, so that we can swap
out the two images.
Once the variables are declared, we need to assign the values to the variables. This is accomplished
with an assignment statement. In this case, we need to use the source property to assign the image to
the variable. Example:
blueArrow.src = “bluearrow.gif”;
This statement tells JavaScript that the source (src) property of the blueArrow object will contain the
graphic image stored in the file bluearrow.gif (sets the source property of the object to that image). It
causes the browser to load the blue arrow image into memory.
USER-DEFINED JAVASCRIPT FUNCTIONS
When JavaScript detects that an event has occurred, it can execute functions to perform various tasks,
depending on the JavaScript statements contained in the functions. For the rollover effect, you want to
initially display the first image on the screen when the page is loaded and then swap the image for the
second image when the mouse pointer rolls over it. To create a function in JavaScript, you use the
5
INTRODUCTION TO JAVASCRIPT
keyword “function” followed by the name of the function. Then you enclose the block of statements you
want the function to execute in curly braces ({ }). Example:
function turnBlue()
{
document.arrow.src = blueArrow.src;
return;
}
The statement “document.arrow.src”, refers to the image “placeholder”, where either image will be
displayed in your page document (the <img> tag in the document). This statement in the above function
assigns the variable “blueArrow.src” to the source property of the image named “arrow”. The image tag
includes the name attribute to allow you to assign a variable name to the image object. Since the arrow
image is part of the HTML document, it can be referenced in JavaScript code as “document.arrow”. The
image tag in HTML would look like this:
<img name=”arrow” src=”bluearrow.gif”>
The source in this image tag would allow the initial graphic displayed on the page when the page is
loaded to be the blue arrow.
The return statement tells JavaScript to return to the next statement in the code after the statement that
caused this function to be executed. To complete the rollover effect, you will need a second user-defined
function to assign the red arrow image to the arrow source property.
EVENT HANDLING LOGIC
Once the variables are declared and the functions are coded, you will need to call the functions based on
the triggering of the appropriate event. The way in which JavaScript code can interact with standard
HTML tags is through event handling logic. JavaScript event handling statements are actually placed
within a standard HTML tag. The statements that handle the onMouseOver and onMouseOut events are
located within the opening anchor (<a>) tag. These statements will be needed to execute the image
swap for the rollover effect. The statements look like this:
<a onMouseOut=”turnBlue()” onMouseOver=”turnRed()”>
In order for the rollover effect to occur when the image is rolled over, the opening and closing anchors
must surround the image tag. The entire code would look like this:
<a onMouseOut=”turnBlue()” onMouseOver=”turnRed()”>
<img name=”arrow” src=”bluearrow.gif”>
</a>
When the onMouseOver event occurs, the JavaScript function called turnRed() is invoked, and this
function sets the source (src) property of the arrow object contained within the document object to the src
property of the redArrow object. In other word, when the mouse pointer rolls over the arrow image on the
web page, the onMouseOver event fires (occurs), and the image source is assigned the contents of the
redarrow.gif file. When the onMouseOut event occurs, the turnBlue() function is called, and sets the src
property of the document’s arrow object to the value of the blueArrow.src property. Moving the pointer
off of the arrow image causes the onMouseOut event to fire, and the image source is assigned the
contents of the bluearrow.gif file.
6
INTRODUCTION TO JAVASCRIPT
HYPERLINK ROLLOVERS
The only difference between an image rollover and a hyperlink rollover is that the hyperlink rollover is
triggered when the user moves the mouse over a hyperlink, rather than when the mouse rolls over the
image. The anchor tags will surround the text used in the text hyperlink, instead of surrounding the
image tag. Example:
<img name=”arrow” src=”bluearrow.gif”>
<a href=”nextpage.html” onMouseOut=”turnBlue()” onMouseOver=”turnRed()”>NEXT PAGE</a>
Now when the hyperlink is rolled over, the image will turn red, but it will remain blue when the image itself
is rolled over.
CYCLING BANNER
A cycling banner is a sequence of graphic images that are displayed one after another with a small
pause between each image change. After all of the images in the sequence have been displayed, the
browser will cycle back to the first image and start the sequence all over again. Creating a cycling
banner takes a single JavaScript event and one JavaScript function.
Since a cycling banner uses multiple images, first you will need to declare an array object. An array is a
collection of similar objects (in this case, images) that can be accessed by means of a variable name and
an index. An index is an integer variable that identifies which element of an array is being referenced.
An array can contain any JavaScript object, but the array for the cycling banner will contain Image
objects. Our example will contain a maximum of four elements (image objects), and its variable name
will be imgArray. The following code is used to declare the variable array:
var imgArray = new Array(4);
This code will create a new array object named imgArray with a maximum of 4 elements.
Once you have declared the array, you will need to give each element in the array a value (in this case,
an image value). First you must declare each element of the array, give it data type (just like you declare
variables) and then you must assign the value to each element. You must also declare a variable to hold
the index for the elements of the array, and its initial value will be set to 0 – the index of the first element
of the array. Example:
imgArray[0] = new Image;
imgArray[0].src = “lions.gif”;
imgArray[1] = new Image;
imgArray[1].src = “tigers.gif”;
imgArray[2] = new Image;
imgArray[2].src = “bears.gif”;
imgArray[3] = new Image;
imgArray[3].src = “wolves.gif”;
var index = 0;
7
INTRODUCTION TO JAVASCRIPT
Now you must create the function to cycle through the images in the array. The code looks like this:
function cycle()
{
document.banner.src = imgArray[index].src;
index++;
if (index == 4)
{
index = 0;
}
setTimeout(“cycle()”, 2000);
return;
}
The images will be displayed on the page in the location where the banner placeholder is located. The
placeholder will be called “banner” and the initial image will be the lions.gif. The code for this is:
<img name=”banner” src=”lions.gif”>
The cycle function will cause the images in the cycling banner to appear one after the other. This is
accomplished by setting the src property of the document.banner object to the src property of the current
element of the imgArray array. The index++ increments the index by 1 each time this statement is
executed. Once the last image is displayed, the index is reset to 0, so the first image is displayed again.
The setTimeout() statement is a JavaScript method that sets a timer to call the cycle function again after
the set amount of time has elapsed (in this case, after 2000 milliseconds have elapsed; 2000
milliseconds = 2 seconds).
The cycle() function is executed using a JavaScript onLoad event, which is embedded in the <body> tag.
This event is triggered when the Web browser has finished loading the body of the HTML web page.
The code for this example looks like this:
<body onLoad=”cycle()”>
In the above example, the browser loads the image called lions.gif (which is assigned the variable name
banner by the name attribute), and then fires the onLoad event, which in turn causes the cycle() function
to be invoked. The cycle() function will then be called continuously every 2 seconds in response to the
JavaScript setTimeout() method, which is called inside the same function.
Randomizing Images
When a site contains a large number of images, you might want them to display in a random order. The
code to accomplish this is actually shorter than the cycling banner. This is due to JavaScript’s built-in
ability to support random number generation. The code will look similar to the code for the cycling
banner. You will still store the images in an array. We will need to include appropriate JavaScript code
to generate a random number, then convert that number into a valid array index in the range 0 to 3 (the
possible indexes for the 4-element array we are using. The function code will look like this:
function select()
{
index = Math.floor(Math.random() * 4);
document.banner.src = imgArray[index].src;
setTimeout(“select()”, 2000);
return;
}
8
INTRODUCTION TO JAVASCRIPT
This select() function will be called from the <body> tag onLoad event. The JavaScript method random(),
which is part of the Math object, is guaranteed to return a real number that is greater than or equal to 0.0
and less than 1.0. A real number, also called a floating-point number, is a numerical value that includes
a decimal position. Since the numbers in this restricted range are not usable as array indices, we need
to scale them to the proper range. In this case, there are 4 elements in the array, so we multiply the
random value by 4. The result is a real number that is guaranteed to be greater than or equal to 0.0 and
less than 4.0. The final step is to invoke the Math.floor() method, which will eliminate the decimal part of
the resulting number. The only possible values remaining are 0, 1, 2, and 3, which are the possible
indices for the array. Thus, the images that will be displayed on the web page will be the image in the
array with the index created by the random number generator method.
JAVASCRIPT SLIDESHOW
In the cycling banner and the randomized banner, the images were automatically changed every 2
seconds. Sometimes it is desirable to let users decide when they want the image to change. By
allowing the user to change the image by clicking on some object with the mouse, the result is an
electronic slideshow.
To code a slideshow, you will code two hyperlinks: one for BACK and one for NEXT. When the user
clicks on one of these links, the image will display appropriately. You will also code two new functions to
call when these hyperlinks are clicked: doBack() and doNext(). You will use the same image array as in
the previous JavaScripts. The functions will use a decision to determine if the index is greater than zero
or less than 3, depending on whether the slideshow is to go back or forward. Here is the code for the
functions:
function doBack()
{
if (index > 0)
{
index--;
document.slideshow.src=imgArray[index].src;
}
return;
}
function doNext()
{
if (index < 3)
{
index++;
document.slideshow.src=imgArray[index].src;
}
return;
}
The first thing you do in both functions is to test the value of the index variable. If it is greater than 0,
then you know that the first image is not being displayed, so you need to back up to the previous image
in the sequence. This is done by decrementing (decreasing by 1) the value stored in the index variable
(index- -) and then loading the previous image source into the slideshow object. If the current value of
index is equal to 0, the doBack() does nothing. If the index is less than 3, then you know that the last
image is not being displayed, so you need to go to the next image in the sequence. This is done by
incrementing (increasing by 1) the value stored in the index variable (index++) and then loading the next
9
INTRODUCTION TO JAVASCRIPT
image source into the slideshow object. If the current value of index is equal to 3, the doNext() does
nothing.
Now you need to set up the hyperlinks so that instead of having a reference to another webpage, it
contains a reference to the appropriate JavaScript function, so that when the user clicks on the
hyperlinks, the click event triggers these functions. The hyperlinks will be coded like this:
<a href=”javascript:doBack()”>BACK</a>
<a href=”javascript:doNext()”>NEXT</a>
The image tag named “slideshow” also needs to be add to the code and given an initial source property
value. This will be the first image that shows in the slide show.
<img name=”slideshow” src=”lions.gif”>
Now you have a user-controlled slideshow. You could also use what you have learned about the
onMouseover event to make the hyperlinks call the appropriate function when the user rolls over the
hyperlink instead of clicking it.
10
Download