This lecture presents a brief example-based summary of client-side programming in JavaScript.
There seem to be more bad books on JavaScript than on any other language.
These may be the best two:
Here are two others that are not so bad:
"use strict";) .
Niederst Robbins describes HTML as implementing the structural component of a Web page, CSS as implementing the presentation component, and JavaScript as implementing the behavioural component.
JavaScript is very similar to PHP (but not to Java!). Like PHP, it is a
dynamically typed language. Differences are that
variables do not start with a dollar character (yay!), constants are defined
differently (const a = 1;), local variables must be declared
(var a = 1;), different open/close script tags are used,
strings are concatenated with a plus character (as in Java and Python),
the object model is quite different,
it (JavaScript) uses event-oriented programming (in Web applications), and
it can be used as a functional programming language. See the
following examples for more differences.
false, true), numbers
(123, 456.7e2), strings ("Hello, world\n"). That's all. Note that values
false, 0, '', null, undefined
and NaN are all interpreted as false in boolean expressions.
Operators. Similar to those in Java and PHP. Use === and !=== for testing equality.
Array types. Literal arrays, e.g., var mixed = [0,
false, "a"]. (See below for more details.)
Object types (cf. PHP associative arrays, Java maps). Literal
objects, e.g., var pm = {first: "Julia", last: "Gillard"}.
Here, first and last are called properties.
Properties may be accessed as pm[first] or pm.first.
Properties may be updated by pm.first = "Tony"; pm[last] =
"Abbott". New properties may be added similarly. So far, similar to
PHP associative arrays. However, functions may be associated with objects.
(Described later.) To iterate over the properties of an object:
for (name in pm) { ... pm.name ... }
Objects may inherit properties from a prototype (or parent) object. To avoid seeing inherited properties, it is possible to write:
for (name in object) {
if (object.hasOwnProperty(name)) { ... object.name ... }
}
Strictly speaking, arrays are a particular kind of object. The indexes of
the array are its properties as an object. The length of an array is one
more than its greatest index. Elements may be deleted from an array
(delete a[3]) without changing its length. Hence, to iterate over
the elements of a dynamic array:
for (index in array) {
if (array[index] !== 'undefined') { ... array[index] ... }
}
This processes the array elements in arbitrary order. You could also use an indexed for-statement, but you may still need to check that array elements are not undefined.
(Indexed) arrays and objects may be arbitrarily nested. This property forms the basis of JSON, described later.
Function definitions. These are superficially similar to function definitions in PHP and Java:
function name (parameters) { body }
But...functions may be stored in data structures, e.g., as
properties of objects, and name may be omitted to define an
anonymous function. It is good practice to declare all local
variables of each function at the start of its body.
In Web applications, JavaScript actions are normally invoked when one of the following events occur:
There are similar functions confirm() and prompt().
Function confirm() displays an dialog box which the user can
accept or reject, and function prompt() displays a dialog box
in wihc a user can enter a text string.
Note that alert is a global variable; in a Web browser, all
global variables are properties of the object window.
Dialog boxes further extend alert boxes and confirmation boxes by allowing users to enter data as well as selecting between two alternatives.
This example is functionally similar to the "Alert box display" example.
Here is the content of file ex3-defs.js:
// Displays message in an alert box
function warning(msg) {
window.alert(msg);
}
To include this external file, write
<script src="js/ex3-defs.js"> </script>in the HTML header. It is good practice to always write JavaScript function definitions in external files, in an attempt to separate the HTML content from the JavaScript behaviour, and to store these definition files in a separate subdirectory (here,
js).
This is a particularly important use case. In forms, we can refer to
an element of a form by form_name.element_name or
form_name['element_name']. If the element has type
input, then we need to write
form_name.element_name.value to get the actual character
string for testing. If the element is a radio button group
(e.g., likes) or a checkbox group (e.g.,
dislikes), we need to write form_name.likes
or form_name["dislikes[]"] (resp.) to get the array
of radio button or checkbox elements. We can then iterate over this
array using the checked attribute as follows to test that one
element has been selected:
elements = the_form["likes"];
for (i=0; i<:elements.length; i++) {
if (elements[i].checked) {
return true;
}
}
return false;
In the "similar example", file doit.php contains only
<?= "Task done." ?>.
This example is simple, but the visibility =
"hidden"/"visible" property is very useful.
See also the ANZ site.
Note that rollovers, tooltips and dropdown menus can also be implemented using CSS.
Note the simple use of the DOM API in these examples for selecting and
changing parts of the browser window. For example,
document.forms returns a list of forms of the current
document, document.forms[0] returns the first form of the
document, and document.forms[0].exButton returns the element
of the form with name exButton.
Important methods for selecting elements of a window (or document) are
getElementById (which returns the unique elment with a given
id), getElementsByName, getElementsByTagName and
getElementsByClassName (all of which returns the list of
elements with the given name / tag name / class name (resp.)).
Having used the DOM API to select an particular element in a document, you
can change the content of that element by assigning to its
innerHTML attribute:
element = getELementById('foo');
element.innerHTML = "<span class='bar'>some new text</span>";
Note also the use of .value to get the value of a form element,
particularly a form element of type input.
Note that syntax errors are not reported by the JavaScript interpreter; it simply generates incorrect behaviour. This can make debugging difficult; be careful.
Many browsers provide features or add-ons to support JavaScript development, an example is Firebug in Firefox.
This simple noughts and crosses program was provided by Chris Gray. It uses the DOM to update elements of a simple HTML table.
This more complex loan
calculator program comes from JavaScript: The Definitive Guide,
Sixth Edition by D. Flanagan (O'Reilly, 2011). It illustrates the use
of the HTML5
<canvas> element as a drawing surface.
Exercise. Rewrite the noughts and crosses program using the HTML5
<canvas> element. This will require detecting events
(mouse clicks) and the location of events on the canvas.
Search for "HTML5 examples" for more examples of sites built using HTML5 and JavaScript. One such example site is HTML5 Demos and Examples.
See pp.310-337 of Web Database Applications, Second Edition by Williams and Lane.
See pp.465-512 of Web Design in a Nutshshell, Third Edition by Niederst Robbins.
Many useful JavaScript scripts for a variety of purposes are easily found on the Web, e.g., at W3Schools' JavaScript Tutorial.
This summary is taken from JavaScript for the World Wide Web by Negrino and Smith. It is used for navigating around an HTML document.
A window has a document, a
frames[] (a list of frames), a location, a
locationbar, a menubar, a name, a
parent, a screen, a self, a
status, a toolbar, a top, and other
elements.
A document has an anchor, an
anchors[] (a list of anchors), a cookie,
a form, a forms[], an image,
an images[], a link, a links[],
a location, a referrer, a title,
and other elements. (In Netscape, a document also has a
layer and a layers[].)
A form has an action,
an elements[], and a method.
An element may be a button, a
checkbox, a hidden, a password,
a radio, a radios[], a reset,
a select, a submit, a text, or
a textarea. Each element has a (containing)
form, a name, a type, and a
value.
Recall that important methods for selecting elements of a document are
getElementById,
getElementsByName,
getElementsByTagName and
getElementsByClassName.
See this chapter from (an old edition of) the definitive JavaScript text for a detailed description of the HTML Document Object Model.
See the W3C Recommendation for full details
The combination of HTML (content), CSS (presentation), DOM and JavaScript (behaviour) is sometimes called DHTML (Dynamic HTML).
Just as we separate content from presentation by using external style
sheets to avoid cluttering the HTML content with presentation information,
so we should also separate content from (JavaScript) behaviour to avoid
cluttering the HTML content with behavioural information. We can use
external JavaScript definition files as a partial solution, but this does
not go far enough. The HTML content will probably still be cluttered with
"javascript: code" links, with JavaScript
"onClick" events, and so on.
See Behavioural Separation and Unobtrusive JavaScript for advice and examples of how to design and implement this separation properly, making essential use of the DOM.
The basic idea of unobtrusive JavaScript is to run a JavaScript function
when a document (without JavaScript code) is first loaded to insert
multiple onevent="JavaScript action" attributes
to selected elements throughout the document.
But details of this technique is more advanced than required for this course.
JavaScript used to be incompletely and inconsistently implemented by different browser developers. It was poorly documented, and there are many examples of bad programming style in books and online tutorials.
However...JavaScript is actually quite a good programming language (if you avoid its many bad parts), since the ECMAScript 5 standard was published (2009) all major browser developers have committed to implementing the standard faithfully, and the texts and documentation is definitely improving.
Moreover...The development of HTML5 with its standard JavaScript API, and the opportunity for scripting multimedia, interaction, HTTP requests and more is making JavaScript more important than ever. The ability to script HTTP requests (i.e., make HTTP requests under program control) in particular, using a combination of JavaScript, DOM and XML (or JSON), called Ajax, is becoming increasingly important as a way to develop applications with rich user interfaces. See below.