JavaScript
CS 4254 - Prof.
Abrams
References
Introduction
-
"JavaScript is a compact, object-based scripting language" [N].
-
Netscape distinguishes two kinds of JavaScript:
-
"client-side" JavaScript: embedded into HTML and interpreted by a Web Browser
-
"server-side", or LiveWire JavaScript: creates server-based applications;
an alternative to CGI programs
Example of Client JavaScript Use
"Client-side JavaScript statements embedded in an HTML page can respond
to user events such as mouse-clicks, form input, and page navigation.
For example, you can write a JavaScript function to verify that users
enter valid information into a form requesting a telephone number or zip
code.
Without any network transmission, the HTML page with embedded JavaScript
can check the entered data and alert the user with a dialog box if the
input is invalid." [N]
The following image is from [N]:
Example of Server-side JavaScript
-
You can use JavaScript for creating server-based applications similar to
CGI programs
-
Server-side JavaScript can
-
connect to relational databases
-
access file system on Web server

How it works: Phase 1:
-
Create HTML pages and JavaScript files.
-
Compile JavaScript into bytecode executable files
How it works: Phase 2:
-
Client requests page
-
Runtime engine (installed on Web server) finds compiled representation
of page, runs JavaScript in page, dynamically generates HTML
-
Generated HTML might add HTML or client-side JavaScript to original HTML
page
Server-side JavaScript Versus CGI-bin
-
Just one file with Server-side JavaScript (vs. HTML + perl, C, ...)
-
JavaScript session management maintains persistent data across client requests,
multiple clients, and multiple applications
-
JavaScript LiveWire Database Service simplifies database access
JavaScript Versus Java
-
JavaScript shares "most Java expression syntax and basic control-flow constructs"
[N]
-
JavaScript is easier for the mass public to use:
-
No class creation - must use built-in objects
-
No static typing, no strong type checking
-
Few built-in types: numeric, Boolean, and string values
-
Purely interpreted (no javac compiler) -- a developer can quickly change
JavaScript and reload Web page
-
Has built-in functions for convenience; developer can add more without
declaration
-
"Descends in spirit from a line of smaller, dynamically typed languages
like HyperTalk and dBASE." [N]
Inserting JavaScript into HTML
Four ways...
Insertion method 1:
<SCRIPT> Tag:
<SCRIPT>
JavaScript statements...
</SCRIPT>
To make your page work with non-JavaScript browsers:
<SCRIPT>
<!-- Begin to hide script contents from
old browsers.
JavaScript statements...
// Double slash must start this line (a JavaScript
comment) -->
</SCRIPT>
Exercise 1:
JavaScript can write text to a Web page using document.write("hello")
Write an HTML file that writes your name to a Web page. (Sample
Output, JavaScript
Solution)
Insertion method 2:
External JavaScript File (on Server):
<HEAD>
<TITLE>My Page</TITLE>
<SCRIPT SRC="script.js">
...
</SCRIPT>
</HEAD>
<BODY>
...
Statements within <SCRIPT> tag are executed if script.js contains
errors.
script.js is a relative URL; it must be in same directory on
server as the HTML file. You can also use an absolute URL.
External files have MIME type application/x-javascript, and thus cannot
contain HTML.
Insertion method 3:
Using JavaScript Expression as HTML Attribute Value
You can use &{JavaScriptVariableName}; on the right
hand side of an equals in normal HTML:
<HR WIDTH=&{barSize};>
So if barSize had value 50, then a 50% wide line would be created.
Note that &...; is the
normal HTML way to include an "entity" (e.g., special character <)
in an HTML document:
Insertion method 4:
JavaScript in Tags to Handle Events
<HEAD>
<SCRIPT>
function compute(f) {
if (confirm("Are you sure?"))
f.result.value = eval(f.expr.value)
else
alert("Please come back again.")
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
Enter an expression:
<INPUT TYPE="text" NAME="expr" SIZE=15
>
<INPUT TYPE="button" VALUE="Calculate"
onClick="compute(this.form)">
<BR>
Result:
<INPUT TYPE="text" NAME="result" SIZE=15
>
</FORM>
</BODY>
Exercise 2:
Add to your HTML page to a button that says "Click me". When the
button is clicked, pop up a box containing your name. (Sample
Output,JavaScript
Solution)
Functions
Function definition consists of
-
The keyword function.
-
A function name.
-
A comma-separated list of arguments to the function in parentheses.
-
The statements in the function in curly braces.
Function call consists of
objectName.methodName(arguments...)
where objectName is name of an object,
methodName
is
name of a method in objectName, and
arguments
is
a comma-separated list of method arguments.
Functions should be defined in <HEAD></HEAD>. Otherwise
function might be called before page is entirely downloaded, resulting
in an error.
Example (from [N]):
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function square(number) {
return number * number
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT>
document.write("The function returned ", square(5),
".")
</SCRIPT>
<P> All done.
</BODY>
Results in the following:
The function returned 25.
All done.
Exercise 3:
Modify your first HTML page to print your name three times.
Do this by defining a function to print your name once followed by a line
break, and call the function three times. Also, you'll need to know
that successive statements in JavaScript are separated by semicolons.
(Sample
Output,JavaScript
Solution)
JavaScript's Page Hierarchy
"JavaScript organizes all elements on a web-page in a hierarchy. Every element
is seen as a object. Each object can have certain properties and methods. With
the help of JavaScript you can easily manipulate the objects." [K]
Consider a simple web page consisting of an image of a horse and a form:
Here is the corresponding hierarchy:
So you could retrieve the value that a user types into the text box and assign
it to a variable with the following:
name = document.forms[0].elements[0].value;
Exercise 4:
Create a Web page containing text field that is empty when the page
is first loaded into your Web browser. Add two buttons to the right
of the text field labeled "First Name" and "Last Name". When you
click a button, your first or last name should appear in the text field.
(Sample
Output,JavaScript
Solution)