I have an ambitious plan which is to produce a series of tutorial lessons
that will cover the full range of JavaScript programming, beginning with
elementary material and continuing all the way into advanced material such
as Dynamic HTML, Style Sheets, etc. Only time will tell if that goal is
achieved.
If you don't have a recent copy of Netscape Navigator, you can download a copy for free from the Netscape Web site. So that takes care of that excuse as well.
Also, JavaScript is fun. There are a lot of really neat things that we can do with JavaScript which provide immediate visual feedback. Visual feedback tends to be fun, and people tend to be more successful in their pursuit of things that are fun than in their pursuit of things that are not fun.
JavaScript is profitable. I could just as easily have chosen to write a tutorial for beginners using the Pascal programming language. Then if anyone finishes the tutorial, nobody else will care.
If I am able to finish writing this JavaScript programming tutorial and you finish it successfully, somebody probably will care, and they will probably be willing to show you how much they care by paying you to write JavaScript programs for them. That makes it even more fun.
JavaScript encompasses modern programming concepts. For example, JavaScript is based on the concept of objects. Object-Oriented Programming (OOP) is here to stay. (For an extensive discussion of OOP, see the early lessons in my online Java programming tutorials.)
A recent survey of high-tech employers in Austin Texas indicated that those employers favor OOP programmers about four to one over programmers with expertise in the older styles of programming.
Although JavaScript is different from other OOP languages (such as Java) in its approach to objects, it is nonetheless object based and provides valuable insight into the use of objects in programming. In fact, it offers insights that other more-conventional Object-Oriented programmers might benefit from.
JavaScript is event driven. Along with OOP, much modern programming hinges on the concepts of event-driven programming and the writing of event handlers. Learning to program using JavaScript provides valuable experience in this important technology area.
To summarize then, I have chosen JavaScript because it is free, it is
fun, it provides a very valuable capability for persons seeking success
in the high-tech marketplace of today, and it is based on the latest concepts
in programming such as objects and events.
There is, however, a co-requisite: knowledge of HTML.
HTML, the Hypertext Markup Language, is currently used to create pages for the World Wide Web that are downloaded, interpreted, and displayed by browsers such as Netscape Navigator. In order to write minimal programs with JavaScript, it is necessary to have a minimal knowledge of HTML. I will teach you that minimal knowledge.
In order to write more significant programs with JavaScript, it is necessary to have a working knowledge of HTML.
I will not attempt to teach HTML at that level. Rather, I will
simply refer you to an HTML tutorial entitled Learning HTML 3.2 by Examples,
by Jukka Korpela, at <http://www.hut.fi/~jkorpela/HTML3.2/>. If
you don't already know HTML, it will be your responsibility to study HTML
concurrently with your study of this JavaScript tutorial so that you will
understand the HTML in the programming examples that I provide.
Why did I select Netscape Navigator instead of the other major brand of browser? I have written and currently maintain a major online tutorial on Java programming which receives several hundred visits by current and aspiring Java programmers each day. I use a counter on my web site that maintains a variety of statistics on those visits. Despite the marketing power of the major competitor to Navigator, in May of 1998, visitors using Netscape Navigator outnumber visitors using other browsers by about three to one. This tells me that the majority of web surfers prefer Navigator over the competing brand, although my statistics may be biased by the fact that the visitors to my site are either current or aspiring Java programmers. It is possible that this population of high-tech visitors isn't representative of the web-surfing world at large.
In any event, I plan to teach using Netscape Navigator. Furthermore,
my plan is to teach JavaScript 1.2 as implemented in Navigator 4.0.
I don't even plan to spend much time looking back to earlier versions of
Navigator (although this may be something that you will need to pick up
on your own).
You will need an installed copy of Netscape Communicator 4.x or later, including Navigator and Composer.
Although Netscape Composer is a pretty good WYSIWYG web page editor, you will also need a good web page editor that is not WYSIWYG (one that allows you to enter HTML tags and JavaScript statements directly into the document). There are dozens available for downloading, some free, and some not free.
I personally favor an editor named Arachnophilia. I favor it for two reasons. First, it is a good editor. Second, I like the author's philosophy.
The author lists the editor as CareWare. What is CareWare?
The following is a copy of some text written by Paul Lutus, the author
of Arachnophilia, that answers that question.
CareWare - What is it?But you are not off the hook yet. The "Payment" for a CareWare program is not monetary. You have to make a different kind of payment altogether. Let me explain. Most Americans are totally dissatisfied with everything. It is too hot,
too cold, too wet, too dry. If we have a free day, we are unhappy because
we don't have two free days. And just about the time we figure out that
we are supposed to appreciate the world as it is, we fall over and die.
If you don't feel a kinship with the statements in the list, then please do one or more of the things listed there. Maybe change how you talk to a young person, or someone whose life would be improved if you related to him or her differently. Or just allow a sense of wonder to re-enter your life, a sense that nothing is deserved and everything contains hidden beauty. And that sometimes beauty is not so much hidden as unobserved. I would like it if you lived your entire life as though each day was your last, as though every small action mattered, in the way that it does when you've run out of time. But I am a realist -- if you do that for just one day, one day of saying the important things, of performing the kindnesses that naturally occur to us when each day might be our last, then you will have paid me for Arachnophilia. I don't ask this because there is some definition of good behavior,
some correct religious or philosophical viewpoint. I ask it precisely because
there isn't such a viewpoint. We are all free agents, we get to choose.
In fact, we must choose -- it's dangerous to let others choose for us.
And no one gets to tell anyone else how to behave -- unless, of course,
one is "selling" software using the CareWare system.
Paul Lutus, Ashland, Oregan |
Once you have downloaded and installed it on your computer, specify
it as the External Editor to Netscape Composer by selecting Edit/Preferences/Composer
and then entering the path to the Arachnophilia directory in the dialog
that appears at that point.
There are two varieties of JavaScript: client side and server side. I'm not going to even try to explain the difference at this point. I will simply state that the early lessons in this set of tutorial lessons will concentrate on client-side JavaScript programming.
Client-side JavaScript statements are embedded in HTML (Hyper-Text Markup Language) documents. A Navigator browser extracts those statements from the HTML and causes them to be executed. Therefore, you must know how to produce the minimal HTML for a document to be compatible with a browser in order to have something to embed the JavaScript statements in.
An HTML document containing the minimal HTML elements plus some comments
and some simple text follows.
<!-- This is an HTML comment --> <HTML> <HEAD> <!-- This is the header portion of the document --> </HEAD> <BODY> <!-- This is the body portion of the document --> <!-- The following text will appear on the browser page --> Hello JavaScript Programmers </BODY> </HTML> |
If you copy the above text into a file, give it an extension of either htm or html, and load it into your browser, the browser should display the words "Hello Javascript Programmers" on the screen.
An HTML document consists of one or more elements. An element
(usually) consists of something that looks like the following:
<Tag> content </Tag> |
I said usually because some begin tags don't require a matching end tag. Again, you can learn all about that sort of thing HTML tutorial mentioned earlier.
By the way, the tags and the content can be on the same line or on different lines. It doesn't matter. Also, HTML is not case sensitive. That means that two matching tags don't have to be written with the same combination of upper and lower case characters. Be careful with this however, JavaScript is case sensitive, so it is a good idea to become very aware of case and to form the habit of pretending like HTML is case sensitive as well.
Included between the begin and end tags is something that is often referred to as content. Content can take on many forms, depending on the needs. The browser uses the surrounding tags to decide how to treat the content.
An HTML document actually consists of one main element with other elements
nested inside of it. The main element is defined by the tags shown
below:
<HTML> CONTENT </HTML> |
For the minimal case, the content of the <HTML> tags includes two other tags that are critical insofar as our JavaScript programming efforts are concerned:
Everything in the header is loaded by the browser before it begins to display the material in the body. For this reason, we will often find it convenient to put JavaScript statements in the header. This will guarantee that the browser has access to those JavaScript statements before it begins to interpret other JavaScript statements in the body. This can be very important from a timing viewpoint.
Another type of HTML element that will be particularly important to
us is a comment as shown below:
<!-- This is an HTML comment --> <!-- This is also an HTML comment --> |
The indicators that signal the beginning and end of the comment can occur on the same or different lines. In either case, everything in between is treated as a comment.
What does it mean to say that something is "treated as a comment?".
For our purposes, it means that the browser doesn't display it on the screen.
Thus, comments are often used to explain what is going on in the HTML in
a way that isn't normally visible to the viewer of the HTML page.
Lets take a look at our first JavaScript script as shown below.
<!-- File Js000020.htm --> <HTML> <HEAD> </HEAD> <BODY> <P>Hello from HTML <BR> <SCRIPT LANGUAGE="JavaScript1.2"> document.write("Hello from JavaScript") </SCRIPT> </BODY> </HTML> |
Hello from HTML Hello from JavaScript |
The first line of output was produced by the normal HTML. The second line of output was produced by the JavaScript statement contained between the <SCRIPT> tags.
Don't worry yet about exactly what this JavaScript statement means. We will learn the details later. For the moment be content to know that it causes the material inside the quotation marks inside the parentheses to be written into the document and displayed on the screen.
Also note the specification of the language shown highlighted in boldface
below. Technically this is known in HTML terminology as an attribute.
Attributes appear as pairs of items separated by an equal sign, and are
used in HTML to specify the value of something. In this case, the
attribute is being used to specify the version of the JavaScript language
being used.
<SCRIPT LANGUAGE="JavaScript1.2"> |
To ensure that users of earlier versions of Navigator avoid problems
when viewing pages that use JavaScript 1.2, use the LANGUAGE attribute
in the <SCRIPT> tag to indicate which version of JavaScript you're using.
Statements within a <SCRIPT> tag are ignored if the browser does not have the level of JavaScript support specified in the LANGUAGE attribute... |
But, what about browsers that don't recognize and support <SCRIPT> tags. Browsers normally ignore tags that they don't understand. That means that such a browser might simply display the JavaScript statements directly on the screen. Normally, this is not what you want to happen.
Therefore, as a concession to the users of such browsers, I am going to show you a technique to avoid having the JavaScript statements displayed on their screen. The technique involves hiding the JavaScript inside of an HTML comment. Then those browsers that don't recognize the <SCRIPT> tag will ignore the JavaScript.
The technique is shown in the following HTML page.
<!-- File Js000030.htm --> <HTML> <HEAD> </HEAD> <BODY> <P>Hello from HTML <BR> <SCRIPT LANGUAGE="JavaScript1.2"> <!-- Begin hiding JavaScript in a comment document.write("Hello from JavaScript") // End hiding JavaScript in a comment --> </SCRIPT> </BODY> </HTML> |
Why is it there, and is it necessary?
Remember that we are dealing with two different processes here. One process is attempting to interpret HTML and display it properly on the screen. The other process is attempting to interpret JavaScript statements and execute them properly. Sometimes these two processes can come into conflict and it is up to us to resolve the conflict.
The // at the beginning of the line causes that line to also be a JavaScript
comment (not an HTML comment) and to be ignored by the JavaScript interpreter.
This is necessary to prevent the characters on that line from causing the
JavaScript interpreter to become confused. In particular, insofar
as JavaScript is concerned, everything on a line following // is treated
as a comment and is ignored.
"Outer quote begins here 'Inner quote inside outer quote' Outer quote and ends here" |
Note that it is possible to disable the processing of JavaScript even
with Navigator, so you can take that into account using a <NOSCRIPT>
tag also. Examples of both are shown below.
<NOSCRIPT> This page uses JavaScript. <BR> If you are using Navigator 2.0 or later, and you see this message, you should enable JavaScript. </NOSCRIPT> |
Earlier in this lesson, I stated that all client-side JavaScript statements are embedded in an HTML document, and I listed four ways to accomplish that. One of the ways was to put a reference to a file containing JavaScript in an HTML document. We will take a look at that approach in this section.
We will modify one of the previous programs to split the HTML and the JavaScript into two separate files.
You can use the SRC attribute of the <SCRIPT> tag to specify a separate file containing JavaScript source code. You can also place JavaScript statements within the same pair of <SCRIPT> tags. Supposedly, these statements will be ignored unless an error occurs and the statements will be executed if an error occurs. For example, this would be useful for announcing an error such as a failure to locate the specified JavaScript file. So far, I have been unable to get this feature to work properly. When I force an error, the JavaScript statements in the <SCRIPT> element that contains a SRC attribute are simply ignored, In fact, they are ignored whether an error does or does not occur.
In any event, whether this feature works properly or not, it is possible to put JavaScript source code in an external file and refer to it from within an HTML file. If the external file containing the JavaScript code is found, that code will be included in the HTML file and executed at the point where it is included.
These external files may be located at any accessible URL. (See the HTML tutorial for a discussion of URLs.) For our case, to avoid syntactical complexity, we will confine them to the current directory on the local hard drive.
External JavaScript files are not allowed to contain any HTML. They must contain only JavaScript source code or comments. The extension on the JavaScript file should be js to increase the probability that the files will be properly downloaded from the server to the client when the external JavaScript file is on a server. This has to do with Multimedia Internet Mail Extension (MIME) types which I will let you investigate on your own.
The following HTML page contains a reference to an external JavaScript
file named JS000040.js. The reference is highlighted in boldface.
Note that the inclusion of the LANGUAGE attribute is mandatory.
Otherwise, the script simply doesn't work.
<!-- File Js000040.htm --> <HTML> <HEAD> </HEAD> <BODY> <P>Hello from HTML <BR> <SCRIPT LANGUAGE="JavaScript1.2" SRC="Js000040.js" > document.write("Unable to open external file") </SCRIPT> </BODY> </HTML> |
//File Js000040.js document.write("Hello from JavaScript") |
Hello from HTML Hello from JavaScript |
Functions, or procedures as they are called in some languages, provide a fundamental building block for virtually every programming language. The purpose of a function is to encapsulate the ability to perform a given task into a single set of code and to be able to invoke or execute that code from a variety of locations within the script. This can eliminate the requirement to repeat the same code over and over when the same task is required at many points in the script.
For example, if you write a script that frequently needs to calculate the surface area of a sphere, you can encapsulate those calculations into a function. Then, whenever your script needs to know the surface area of a sphere, it can simply call the function providing the radius of the sphere as a parameter. The function will perform the calculation and return the answer to be used by the script at that point.
A JavaScript function definition has the following basic parts:
The definition names the function and specifies how it will behave when it is called.
The call to the function temporarily passes control to the statements in the function causing them to behave as previously defined. Once the statements have been executed, control is returned to the point in the script where the call was made.
As in the sphere example discussed above, it is often useful to pass information to the function for it to use in doing whatever it is supposed to do (but this is not always required). When we call the function, we include parameters in the call to the function that match up with the argument list mentioned above. That is the mechanism for passing information to a function. This will probably make more sense when you see an example.
Remember that we are dealing with HTML pages that are normally downloaded from a server. The download process often experiences delays. You should define all of your functions in the header portion of the HTML page. That will ensure that all functions are defined before any of the content of the page is displayed. This will prevent the user from taking an action that needs the function before it is fully defined.
Usually (but not always), the purpose of a function is to calculate or otherwise determine some value and return it. In the sphere example mentioned earlier, the purpose of the function would be to calculate and return the surface area of the sphere. Returning a value is accomplished using the return keyword in the body of the function.
The following sample HTML page uses JavaScript to define a function named getHalf() in the header portion of the page. This function is somewhat simpler than one that could be used to calculate the surface area of a sphere, but the basic concept is the same. This function expects to receive a parameter. It calculates and returns half the value of the incoming parameter.
The function is called twice in the body of the page, passing a different value for the parameter each call. The call to the function is embedded into the argument list of a call to a different function named write (this is a special kind of function that we will call a method). For the time being, let it suffice to say that the method named write will display its arguments on the screen.
In other words, this script makes a call to the function named getHalf() passing a parameter to that function. That function returns a value that is half the value of the incoming parameter. (As a practical matter, the call to the function is replaced by the value that it returns.) This value is than passed as a parameter to the method named write() where it is displayed on the screen.
It is a principle of good programming design that each function should
perform only one task, and should perform it well. The task performed
by the function named getHalf() is to calculate and return half
the value that it receives, and it does it well.
<!-- File Js000050.htm -----------------------------------> <HTML> <HEAD> <SCRIPT LANGUAGE="JavaScript1.2"> <!-- Hide script //Define the function named getHalf() function getHalf(incomingParameter) { return incomingParameter/2; }//end function getHalf() // End hiding --> </SCRIPT> </HEAD> <BODY> <SCRIPT> //Call the function passing 10.6 as a parameter. document.write("Half the number is: ", getHalf(10.6),"<BR>"); //Call the function again passing 12.3 as a parameter. document.write("Half the number is: ", getHalf(12.3)); </SCRIPT> <P> Done. </BODY> </HTML> |
We will discuss JavaScript expressions in more detail later. For the moment, let it suffice to say that in virtually all programming languages, including JavaScript, expressions are evaluated to produce a value. The value produced effectively replaces the expression in the statement.
A JavaScript expression can form the value side of an HTML attribute. This is technically referred to as a JavaScript entity. You can learn what is normally meant by the word entity in the HTML tutorial that I referred you to earlier.
Entity values are evaluated dynamically. This makes it possible to write JavaScript expressions wherein the value given to an attribute can change depending on other circumstances within the JavaScript script.
The HTML tutorial will tell you about character entities which allow you to define characters with special numerical codes or names by preceding the name with an ampersand (&) and terminating it with a semicolon (;). For example, you can include a greater-than symbol (>) with the character entity > and a less-than symbol (<) with <.
JavaScript entities also start with an ampersand (&) and end with a semicolon (;). However, instead of a name or number, you use a JavaScript expression enclosed in curly braces {}.
You are allowed to use JavaScript entities only in those places where an HTML attribute value would normally be found.
The following HTML page defines and uses a JavaScript function to set the color of some text. The name of the function is returnRed() and it is designed to return the string value (for the time being, a string is simply a series of one or more characters used together) that is used to cause HTML text to be rendered as red.
For demonstration purposes, color is applied to two separate lines of output text. The first line, which reads "Color me blue" is rendered blue using a standard HTML <FONT> tag with a COLOR attribute. The attribute value #0000ff causes the text to be rendered as blue. (Hopefully we will have time to explain why in some subsequent lesson.)
The second line of output text also uses a standard <FONT> tag with a COLOR attribute. However, in this case, the attribute value is not hard-coded into the HTML statement. Rather, in this case, the attribute value is obtained by making a call to a function named returnRed() which just happens to return the required attribute value for rendering the text as red.
However, this function could be made more complex in which case it could
return different values based on something else that is happening in the
script. In this way, the color in which the text is rendered could
be determined at runtime rather than specifying it when the HTML author
designs the page.
<!-- File Js000060.htm -----------------------------------> <HTML> <HEAD> <SCRIPT LANGUAGE="JavaScript1.2"> <!-- Hide script //Define the function named returnRed() function returnRed(){ return "#ff0000"; }//end function returnRed() // End hiding --> </SCRIPT> </HEAD> <BODY> <FONT COLOR=#0000ff>Color me blue</FONT><BR> <FONT COLOR=&{returnRed()};>Color me red</FONT> </BODY> </HTML> |
In a financial statement, it could cause the text to be rendered as
either red or black, depending on whether the business was "in the red"
or "in the black."
The write() method takes any number of string arguments. They can be string literals or variables (we will also have more to say about literals and variables later).
You can also use the string concatenation operator (+) to create one string from several when using write().
-end-