JavaScript
Microsoft had hoped that VBScript would emerge as the premier scripting
language for use on the web, but the title clearly belongs to JavaScript -
arguably the most used language on the web! I use Perl for CGI scripts
and JavaScript for web page scripts - in both cases because Microsoft
products (VB and VBScript) fail to provide a solution compatible with
most servers or browsers. As a VB programmer you should learn to decide
which tool can be help you get the job done, then use it!
Return to top of document
JavaScript History
Before I get too far into this tutorial, let me highly recommend that after
you read it you should head over to the Netscape tutorial and work through
it as well. It's an excellent read, although it helps immensely if you have
a reasonable understanding of JavaScript first.
Now, let's talk about ECMA-262, JavaScript and JScript. The European
standards organization ECMA has released ECMA-262. This document covers
scripting for use in web pages. Netscape and Microsoft both have versions
of this script. Netscape has JavaScript and Microsoft has JScript. Each
supports the ECMA standard but each also has added their own unique
extensions to the language.
Gosh, it sound almost like the browser wars again! But it's not really that
bad unless you're trying out some of the advanced features. In my experience
both browsers (Netscape Communicator and Microsoft Internet Explorer) handle
scripts pretty much the same. I use Netscape documentation for learning but
I develop all my scripts within Internet Explorer. This approach seems to
work out pretty well.
And yes, there are other browsers out there. But, I have an inflexible
attitude about that as well. Given that I have a limited time, and
especially given that the vast majority of my users are from Netscape
or Microsoft browsers, I simply give no attention to the abilility of
other browsers to run my scripts correctly. If a user from a particular
browser makes me aware of a problem, I will certainly work the issue.
I spend no time at all trying to make my scripts be common to any
but the "Big 2" browsers.
One additional thing to remember is that JavaScript is not a "light"
version of Java. The two languages are completely independent of one
another. JavaScript is a Netscape invention and the company Sun Microsystems
was the developer of Java.
On the topic of terminology, you will find that the term JavaScript is the
standard terminology on the web. Everyone knows that Microsoft has their
own script technology name (JScript) but hardly anyone uses it.
As a web site developer I am forced to use only scripts which seem to work
in both browsers. Not only do the browsers from both companies have some
differences, it turns out that different versions of browsers within the
same company don't even work the same. My attitude is that since the browsers
are free, I write for version 5 of each browser and if a user has trouble with
it, then they need to update anyway ! I simply don't have time to create
scripts that determine which browser/update a user has and then to custom
tailor my scripts for that version.
Actually, since Netscape was the originator of JavaScript (ECMA is essentially
an after-the-fact standardization of what Netscape developed), I've found
that their documentation and implementation of a scripting langauge is the
de facto standard. Microsoft is playing catchup and works to make sure that
JScript is compatible with JavaScript.
One thing you'll see if you go to each of their sites is that through the
use of their own customization of the ECMA scripting technology, that both
are trying to add features which will enforce the use of their version of
JavaScript. Microsoft is particularly trying to encourage the integration
of JavaScript, ActiveX technology, Visual Basic Script, and their server
technologies. In fact, both companies are pushing hard to move the
technology forward - Netscape to maintain the lead and Microsoft to catch up.
Bottom line is that the differences don't really come into play for most
basic scripts. The more advanced the script, the more opportunity there is
for conflicts. If you're like me, and have both browser on your PC, you
can always simply check to make sure your scripts are doing what you expect.
Return to top of document
JavaScript Overview
JavaScript is simply a block of text (i.e., line of code) that you place
into an HTML file which your browser can read and treat as a set of
instructions. It is not unlike the old DOS batch files, but much more
complex. It is similar to QBasic except that it can be placed inside
another document (in this case, an HTML file) to take action on the document
itself or to interact with a user. Like DOS batch files and like QBasic
programs, JavaScript is an interpreted language. Each browser ships
with a built-in JavaScript interpreter which reads the code lines and
executes the statements without the need for precompiling the code.
But, unlike those predecessors JavaScript is geared only towards providing
interactivity with a user by controlling the content/display of an HTML page.
One big difference between web page script languages and their predecessors
is that JavaScript (or VBScript) cannot read or write to your hard disk. This
is done entirely for security reasons - to prevent someone from embedding a
JavaScript in a page which would extract or damage information on your PC.
One of the things you will find is that JavaScript follows the programming
industry standard of using objects. As a VB programmer you'll be somewhat
familiar with the concept already, so learning JavaScript will feel like
an extension of things you already know.
What JavaScript does, and does very well, is to give more control over
web pages than HTML alone can provide. It allows a web page to respond to
the actions of the viewer - change how or what information is displayed
in response to user inputs - interactively!
Let's clarify one thing. When a browser reads a JavaScript it executes it
right then and there - as part of creating the layout for a page. The
layout of a page cannot change unless you reload the page. Some information
on the page can change real-time, such as the text in a text box or an
image on a page. I'll talk more about this further into the tutorial.
Return to top of document
Embedding JavaScript in HTML
JavaScript is very easy to place in an HTML file. We'll cover the JavaScript
code shortly, but all you have to remember is to place the following two lines
into the HTML file:
<script name="myscript">
</script>
or this
<script name="myscript" src="myscript.js" >
</script>
Actually, any scripting language would use the same two lines, but since the
only scripting language that both Netscape and Microsoft Internet Explorer
support is JavaScript, these two lines have become synonymous with JavaScripts.
Since an HTML page can have more than one script the "name" attribute is used
to distinguish between them. As we will see shortly, the naming of scripts
will also prove useful in writing interactive code. The second example in
the code above shows that you can also chose to save your script into
a file and have your browser read it from the server.
So how do you get a JavaScript to run? Consider this short example:
<script>
document.write("Hello world!")
function SayGoodbye()
{ document.write("Goodbye!") }
</script>
As a browser is loading a page it executes the contents of a JavaScript
as soon as the script is read. In this example, the browser would read the
script and write the words "Hello world!" on the screen as part of your web
page. The string "Goodbye!", however, will not be written until you
specifically call out the function "SayGoodbye" that is contained within
the JavaScript.
While some JavaScripts do not contain functions - i.e., the page is designed
so that the running the script as the page loads is all that is needed, such
as for display of local time, or of a random message to the web page visitor
- almost all JavaScripts use functions which must be specifically called by
a user action. In the next section on Objects you will see that JavaScript
objects have events - code which executes when a user action takes place.
A JavaScript function can be called during one of those events. The syntax
and an example for this is:
Syntax
<tag onEventName="MyFunction();" /tag>
Example
<a href="tutor.htm" onClick="go_there();"> Tutor Home Page </a>
The first line is the general syntax. You simply use an equality to set
the eventname to the JavaScript function (or statements) to be run when the
event takes place. In the example, the tag is modified to have a function
called "go_there" to be executed when the user clicks on the "Tutor Home Page"
link. Note that the onClick instructions over-ride the normal link function
that a user would see if onClick were not included.
Finally, it is common practice to put your JavaScript code between HTML
comment lines like this:
<script name="myscript">
<!--
--script code goes here
//-->
</script>
The reason for this practice is that some older browsers will not correctly
recognize scripts. By putting the code within HTML comment lines, the older
browsers will ignore the scripts. This practice is still prevalent, but with
the pace of progress in browsers and given that Netscape and Microsoft cover
the majority of the market, whether you use this practice is less of an issue
than it was just a few years ago.
Finally, when writing a JavaScript you may want to include your own
comments to help you understand the flow of the program. Comment lines
begin with two backslashes "//". For a multiline comment, start the
first line with a "/*" and end the last line with a "*/"
Return to top of document
JavaScript Objects
Since you're at my VB tutorial site, you will likely already have some
programming background. This means you probably have a working knowledge
of objects - including the concepts of properties, methods, and events.
To be a JavaScript programmer you have to make use of the objects exposed
by both JavaScript and by your browser. No, JavaScript is not
object-oriented in the full classical sense, but it does use objects and
is considered to be object-based.
In this section we will cover JavaScript objects. Browser objects are
covered in the section beyond that. However, a short reminder is needed
here. Microsoft and Netscape are in a constant struggle for control of
the commercial markets. Each provides slightly different versions of
JavaScript and each have a slightly different object model for their browser.
As one adds features, the other plays catch-up. In my tutorial I try to
present only common capabilities between the two, but as your expertise grows
you will find that some taliloring of a JavaScript to the selected browser
may be necessary.
Scripts that work well in Netscape Communicator may not work at all in
Microsoft Internet Explorer. This holds for other browsers on the market
as well, some of which do not support JavaScript at all!
Now, let's talk about JavaScript objects! Fortunately, there are only
three: String object, Math object, and Date
object. These objects have no events, only properties and methods as given
below. JavaScript also supports several built-in functions, not associated
with the three built-in objects. Those too are listed below.
- String Object
- Properties
- length - the numer of character in a string
- Methods
While there are about 19 methods, you should note that most of
them simply create a string with HTML tags around it so that you
can more easily format any text that you create from within a
JavaScript. The exceptions are for converting a string to lower
or upper case, searching for a specific string within another
string, or returning a portion of a string
anchor(namedAttribute) - wraps in <A></A>
bit() - wraps in <><>
blink() - wraps in <><>
bold() - wraps in <b></b>
charAt(index) - wraps in <><>
fixed() - wraps in <><>
fontcolor(color) - color is in rrggbb hex format
fontsize(size) - size is 1 to 7, and + or - relative
indexOf(searchValue,[fromIndex]) - search string forward
italics() - wraps in <i></i>
lastOf(searchValue,[fromIndex]) - search string backward
link(hrefAttribute - wraps in <a href...></a>
small() - wraps in <><>
strike() - wraps in <><>
sub() - wraps in <><>
substring(indexA, indexB) - returns part of a string
sup() - wraps in <><>
toLowerCase() - converts string to lower case
toUpperCase() - converts string to upper case
- Math Object
- Properties
The properties of the Math object are actually eight
constants which are available for direct use, avoiding the need
to program your JavaScript to calculate them.
E - Euler's constant 2.718
LN2 - natural logarithm of 2 - 0.693
LN10 - natural logarithm of 10 - 2.302
LOG2E - Base 2 logarithm of e - 1.442
LOG10E- Base 10 logarithm of e - 0.434
PI - Ratio of circumference to diameter - 3.14159
SQRT1_2 - Square root of one-half - 0.707
SQRT2 - Square root of two - 1.414
- Methods
The methods of the Math object are simply common mathematical
functions which you may need when writing your scripts. These
methods are similar to those found in any other programming
language.
abs(number) - absolute value
acos(number) - arccosine
asin(number) - arcsine
atan(number) - arctangent
ceil(number) - next integer higher or equal to number
cos(number) - cosine
exp(number) - e raised to the number
floor(number) - next integer less or equal to number
log(number) - natural logarithm of number
max(number1, number2) - greater of the two numbers
min(number1, number2) - lesser of the two numbers
pow(base,exponent) - raises base to the power of exponent
random() - randome number between zero and one
round(number) - number rounded to nearest integer
sin(number) - sine
sqrt(number) - square root
tan(number) - tangent
- Date Object
Unlike the String and Math objects which are automatically created,
the Date object must be specifically created within the JavaScript
in one of four ways:
myDate = new Date()
myDate = new Date("monthday, yearhours:minutes:seconds")
myDate = new Date(year,month,day)
myDate = new Date(year, month, day, hours, minutes, seconds)
- Properties
The Data object has no properties.
- Methods
There are nine Data object methods.
getDate() - day of the month
getDay() - day of the week
getHours() - hour of the day
getMinutes - minutes of the hour
getMonth - the month
getSeconds - seconds of the minute
getTime - milliseconds since 1/1/1970
getTimeZoneOffset - offset between local time and GMT
getYear - the year
toGMTString() - convert date to GMT format
toLocaleString - convert to locale format
parse - converts local time to milliseconds since 1/1/1970
UTC - returns GMT time as milliseconds since 1/1/1970
Built-In Functions
These six built-in functions (methods) are not associated with any
of the 3 objects mentined above but my be used freely within your
JavaScript program. The eval function is easily the most used
function of the group.
- eval(string) - evaluates an expression to return a number
- parseFlot(string, [,radix]) - extract floating point number from string
- partsInt(string, [,radix]) - extract Integer from string
- isNaN(testvalue) - UNIX only, returns True or False (NaN = not a number)
- escape("string") - converts to ASCII
- unescape("string") - returns ASCII
Return to top of document
Browser Objects
The strength of JavaScript comes from what it can do with the display of
the web page. This control is made possible by the browser's exposure of
its own object heirarchy. Without such exposure, JavaScript would be pretty
much useless. Thus, you have to understand the browser object model to be an
effective JavaScript programmer.
The model is not identical for both Netscape Communicator and Microsoft
Internet Explorer, but close enough for the majority of applications. As
best I know, the object model shown below is common between the two.
Common Document Object Model
browser---window---frame
---location
---history
---document---layer
---link
---image
---plugin
---area
---applet
---anchor
---form---element---button
---checkbox
---fileupload
---hidden
---password
---radio
---reset
---select
---submit
---text
---textarea
The window object is at the top of the heirarchy. Here are its
properties and methods.
- Properties
- defaultstatus
- frames
- length
- parent
- self
- status
- top
- window
- methods
- close
- conform("message")
- open
- prompt("message,inputDefault")
- timeoutID
- clearTimeout(timeoutID)
The location and document objects are the two which will
likely receive most of your programming efforts. Here are details on their
properties and methods:
- location object
The location object has no methods
- Properties
- hostname
- port
- pathname
- search
- hash
- href
- host
- document object
- Properties
- bgColor
- fgColor
- linkColor
- alinkColor
- vlinkColor
- lastModified
- location
- referrer
- title
- cookie
- Methods
- write
- writeln
- open
- close
- clear
As the document model showed above, the document object itself consists
of several objects which you can use within your JavaScript programs.
Easily, the form object is where most of your programming will be, but
before getting to the form object I'll first cover two lesser objects,
the anchor and link.
The anchors object consists of all the anchors which are of the
form <a> name="whatever" </a>. You can access the array
using the following syntax:
document.anchors(0) to document.anchors(document.anchors.length-1)
The linkobject consists of all the anchor object of either the
form <a> name="whatever" </a> or the form
<a> href="mypage.htm" </a>. You can access the array
using the following syntax:
document.link(0) to document.link(document.link.length-1)
Within the document, the form object provides the most
useful interface. Its interface is list below. The actual event
names are pretty much descriptive of the user action so a lot of detail
isn't necessary. I also show the specific elements of a page for which
the events apply. For example, the onLoad event applies to the document
window, but not to any of the form text elements on the page.
- Events
- onBlur - user removes focus from a form element
Applies to: select, text, textarea
- onChange - user changes value of a form element
Applies to: select, text, textarea
- onClick - user clicks on a link or a form element
Applies to: button, checkbox, link, radio, reset, submit
- onFocus - user sets focus on a form element
Applies to: select, text, textarea
- onLoad - page is loaded into the browser
Applies to: window
- onMouseout - user moves mouse off a link or anchor
Applies to: link
- onMouseover - user moves mouse over a link or anchor
Applies to: link
- onSelect user selects a form element's input field
Applies to: text, textarea
- onSubmit - user submits a form
Applies to: form
- onUnload - user exits the page
Applies to: window
- Methods
The is only one method for a document.
- submit
The form object also support the forms array whose properties
are as follows.
- action
- element - array of element objects defined in the form
- encoding
- length - number of entries in the element array
- method
- target
Return to top of document
JavaScript Variables
JavaScript recoginizes only four variable types:
- Numbers - covers integer and decimal numbers
- Strings - conventionl string
- Boolean - true or false
- Null - undefined or no value
To use a variable in JavaScript you simply include it in the script - no
declaration of the variable is required. Variables must start with a letter
or underscore but may otherwise have numerals in the name.
Remember that I mentioned earlier that a web page can have more than one
script on it? That becomes important in this discussion on variables. If you
use a variable in one script, it automatically becomes avaialable in every
other script on the page! If both scripts use and change the same variable
you can easily get unexpected results.
To work around that problem, JavaScript offers the ability to define a
variable so that it is available only to that script! Here's how:
var myVariable = 10
Using the "var" keyword stops any other script from seeing "myVariable". This
means each script could define its own variable "myVariable" and each would
have its own independent value. In such a case, "myVariable" would be known
as a "local" variable rather than a "global" variable.
When you use string variables you can enclose them with single or double
quotes. When a string is to be used as an argument within double
quotes, you must enclose the string within single quotes.
Also with strings, the following special characters can be represented by the
following:
- backspace - \b
- form feed - \f
- newline - \n
- carriage return - \r
- tab - \t
Return to top of document
JavaScript Operators
As you would expect, JavaScript lets you write expressions similar to what
you would see in VB and other programming languages.
The +, -, /, *, <, >, <=, >= and ^ operators apply as usual.
Other operator syntax includes:
- && - Boolean AND
- | - Boolean NOT
- || - Boolean OR
- % - Modulus
- == - Equal
- |= - Not Equal
JavaScript also supports several shorthand assignment operators which are
similar to C++ or Perl coding syntax. This is not the complete list,
but does cover the most used operators.
- += : x+=y is the same as x = x + y
- -= : x-=y is the same as x = x - y
- *= : x*=y is the same as x = x * y
- /= : x/=y is the same as x = x / y
- %= : x%=y is the same as x % y (modulus)
Return to top of document
JavaScript Control Statements
Here's where some of the real work in JavaScript gets done. By using the
following control statements you are able to add animation to a page,
make its content dynamic, or allow for interaction with the user. These
statements are functionally identical to control statements found in all
programming languages.
In the examples to follow, the braces {} are used to enclose a series
of JavaScript statements. You can put the braces on separate lines or
on the same lines as the code.
In addition to the code shown for the following control statements,
JavaScript offers two special statements which can modify the way in
which code executes in a script.
- break
when executed within a control loop, causes execution to exit from
the control loop
- continue
terminates the execution of the current loop, then begins execution
with the next iteration of the loop.
Here are the various control groups available for use in your JavaScripts.
Use this to execute a block of statements if a condition is true.
if (condition)
{ statements; }
Use this to execute one block of statements if a condition is true or
a second block of statements if a condition is false.
if (condition)
{ statements; }
else
{ statements; }
Use this construct to execute a block of instructions a fixed number
of times. The number of loops can be a simple integer, or even an
expression.
for (initial-expression; condition; increment-expression)
{ statements; }
This loop will continue while the condition is true. The statements will
not execute at all unless the condition is initially true.
while (condition)
{ statements; }
This loop will continue until the condition becomes false, but is
assured of completing the statements at least once.
do
{ statements; }
while (condition)
This next capability is especially useful to programmers. The for..in
control loop will cycle through each property of an object or each element
of an array.
for (variable in object)
{ statements; }
Finally, if you get tired of typing, when you want to execute a series of
statements using the same object, you can use this:
with (object)
{ statements; }
Return to top of document
JavaScript Functions
As was mentioned earlier the contents of a script will execute immediately
on loading of a web page, except for the code contained in functions.
Functions must be specifically called before the code will be executed.
The syntax for a function is similar to a VB Sub function:
function MyFunctionName(arg1, arg2, ...)
{
statements
return myvariable
}
To call the function you simply use the "MyFunctionName" with the
arguments as a statement in the JavaScript (arguments may be numbers,
strings, expresssions or objects).
MyFunctionName (10,23)
MyFunctionName (varX, varY)
MyFunctionName (varX*varY, varX+varY)
A function does not have to return a value, but can do so. Unlike VB,
where the return value is set by setting the function name to a value, a
JavaScript function simply identifies the expresssion or variable whose
value is to be returned (see the example above).
Functions are normally accessed by placing the call to the function in
the code for one of the many event handlers.
If you do include arguments in the call to a function, those arguments
are automatically available as variables - an explicit argument declaration
using the "var" is not necessary and will have values based on the value
contained in the function call. However, for other variables used within
a function use of the "var" declaration is required.
Return to top of document
Sample JavaScripts
Reading tutorials are just fine, but it is when you see and use the code
that it all comes together. Here are several examples of simple scripts.
Remember that applying JavaScript consists of the following actions:
- Place the script into the HTML file
- Place functions within the script. Anything outside a function will
be executed automatically as the page loads. Functions only execute
when specifically called.
- Place code within HTML tags to respond to user actions (events)
Now for the code:
- Display an Alert box
<script name="myscript">
alert("Welcome!")
</script>
- Display a Confirm box
<script name="myscript">
var answer=confirm("Go there?")
if (answer)
{ window.location="newpage.htm" }
</script>
- Display Prompt box
<script name="myscript">
var answer=prompt("Enter your name.")
alert("Hello" + answer)
</script>
- Set Form Background Color
<script name="myscript">
document.bgColor = "blue"
</script>
- Set Text in Window Status
<script name="myscript">
window.status="Welcome to my page!"
</script>
- Set Text in Window Status on MouseOver
<script name="myscript">
<a href="mypage.htm" onMouseover="window.status='active link';return true"
onMouseout="window.status=''">My Page</a>
</script>
- Display Document Date
<script name="myscript">
document.write(document.lastmodified)
</script>
Use a Link as a Submit Button
First, create this link somewhere on the page
<a href="javascript:document.myform.submit()">Go There</a>
Second, create a form named "myform"
<form name="myform">
</form>
Image Flip
<a href="mypage.htm" onMousover "if(document.images.menu.src='after.gif'"
onMouseout "if(document.images.menu.src='before.gif'">
<img src="before.gif" name="menu"></a>
Check for Valid Email
First, create this form:
<form name="example">
<input type="text" name="email" onBlur="emailcheck()">
</form>
Second, create this script
<script name="myscript">
function emailcheck() {
var EmailString=document.example.value
if (EmailString.indexOf("@")==-1)
{ alert("Please re-enter email address")
document.example.email.focus() }
}
</script>
Return to top of document
Web Sites
There are two kinds of sites which will help you develop expertise with
JavaScript - general purpose tutorial sites which provide JavaScript
information and JavaScript-specific sites which are focussed on
JavaScript tutorials and code. Then, there is the home site of the
actual languages themselves (one for the Netscape version and one for the
Microsoft version).
- General Reference Sites
- JavaScript-specific Sites
- Document Models
|