Introduction to JavaScript


About this Document

This document is Copyright (c) Information Technology Group,
www.itgroup.ro, Alin Avasilcutei, Cornel Paslariu, Virgil Mager
.

Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.2
with no Invariant Sections, no Front-Cover Texts, no Back-Cover Texts.

This document is an introduction to some of the most frequently used components of the JavaScript programming language. The various language characteristics and elements are gradually introduced, attempting to create a document structure such that each new element being presented to rely as little as possible on elements that are introduced at a later time (this is not always possible, as some language features are intr-related in a "circular" way).

The reader of this document is assumed familiar with the basic structure of a simple HTML document, as well as with the C programming language.





What is JavaScript

JavaScript is a scripting language, designed for being embedded in HTML documents, and exectuted directly in an HTML browser. The following diagram illustrates how a JavaScript program interacts with the display objects described in an HTML document, and thus (indirectly) with the user (reader) of the document.
          HTML Browser   <---------------------------------------\
| |
|interprets |can request the browser to perform
V |certain actions, such as to
HTML Document |re-display the document, to send
| |some data (e.g. enetered by the user
|contains |into an HTML form) to a server,
V contain |to clear the browser window, to
HTML elements ----------------------> Script elements |open a new browser window containing
^ | |another HTML document, etc
|reflect |contain |
| interact with V |
Browser objects <----------------------> JavaScript ------/
^ Programs
|user-interface for
|
Display objects
^
|interacts with
|
USER (reader)

The following example illustrates the structure of a JavaScript/HTML document that contains an HTML button, such that a random number will be displayed in a pop-up window every time when the button is pressed. Such a structure essentially consists of:
 <html>                                      <!-- the start of the HTML document -->
<head> <!-- the document header element -->
<script> /* the script element that contains the function */
function printRandomNumber() { // the function definition
alert(Math.random()); // display a message box with a random number
} // (Math.random() generates a random number [0...1) in JavaScript)
</script>
</head>

<body> <!-- the document body -->
<input type="button" /* the button element */
value="print random number" /* the text displayed on the button */
onClick="printRandomNumber()" /* capture the user clicks on the 'button' display object */
/>
</body>
</html>
When the document outlined above will be loaded in an HTML browser, the following succession of events will occur: After the above sequence has been completed, the browser window will show a page containing a a button, and every time the button will be clicked (i.e. "pressed"), a new random number will be displayed in a pop-up message box.


Code block

A JavaScript Code Block is similar to the C code block, and is the basic container for JavaScript sequential code; it may contain any or all of the following:
  { // the Code Block begins with '{'
variable declarations/definitions
statements, expressions, and/or other code blocks (wich in turn may contain other code blocks, etc)
} // the Code Block ends with '}'
(the following sections detail the above categories)



Data model overview




Expressions and Operators

The expressions and operators in JavaScript are very similar to C expressions and operators. An expression is a succession of JavaScript keywords and/or tokens that a JavaScript interpreter can evaluate to produce a value.


Functions

JavaScript functions are similar to C functions, with the main difference that they do not use data types for neither their return value (if any), nor for their arguments (if any). Following is an outline of the most important characteristics of JavaScript functions:


Statements

The JavaScript statements are similar with C/C++ statements.
Note: the FOR - IN and WITH statements, which are specialized in manipulating objects, are discussed in Manipulating Objects chapter.


Exceptions

A JavaScript operation can run into an "exceptional state", which is a situation where the normal flow of the program can nolonger continue (e.g. attempting a division by zero, or calling an undefined fumction, etc). These situations can be "caught" by the dedicated 'try-catch' syntactical contruct, which is very similar to the 'try-catch construct on C++ or Java.
Apart from the inbuilt situations that may cause exceptions, a user-defined function (or any other user code block) can itself force the generation of an exception via the 'throw' statement. In this case, the execution of the code is immediately abandoned (after the execution of the 'throw' statement), and an attempt is made to find an "enclosing 'try' statement" (a 'try' code block that "wraps" the point where 'throw' was executed). If such a 'try' block is found, then execution is resumed at the 'catch' block that corresponds to that 'try' block; else, JavaScript execution is terminated with an irrecoverable exception condition.


Objects overview

JavaScript 'objects' are data structures that group together a number of elements, with said elements being referred to as the object properties.
The only way to create an object in JavaScript is using the dedicated 'new ObjectTypeName' operator which creates a new object of type 'ObjectTypeName', and returns a pointer to it such that the object can later be handled within a program. There is no other way to have access to a newly created object except via the pointer to it that is returned by 'new' upon creation.

A special predefined JavaScript type is 'Object' which represents an "empty" data structure, i.e. a data structure with no properties. Based on the 'Object' type name one can create new instances of "empty objects" using the syntax 'new Object':
 var myObject = new Object;  // the variable 'myObject' now holds a pointer (a reference)
// to the object that was created by the 'new' operator
var isObject = (typeof(myObject) == 'object'); // isObject will be set to boolean 'true'
A variable that "holds" a pointer to an object is referred to as an object variable.



Inbuilt Objects

JavaScript provides in-built objects that deal with date and time, math, strings, regular expressions, numbers, and other useful entities.


Manipulating Objects



Timer functions

Apart from the "traditional" in-order execution of statements, JavaScript provides several dedicated functions for executing a specified function periodically, or at a designated time (specified as a delay). These functions are not part of the "core" JavaScript language, but rather they are implemented by the browser in which a JavaScript program is running. The details on these functions are presented in the 'HTML Integration' chapter, the 'Timer methods' paragraph later in this document.



HTML Integration

JavaScript by itself is no more then a programming language; in order to make use of it for creating dynamic web pages (i.e. pages in which the content changes depeding on the user interaction), a number of mechanisms are provided for integrating JavaScript programs with the contents of an HTML document. The main "integration directions" are the following: The following sections present how a JavaScript program is embedded inside an HTML document, how a JavaScript program can read the properties, and change the appearence, of the display objects associated with the HTML elements in a document, and how an event that occurs in conjunction with a specific display object (e.g. the user pressing a specific button) can be "intercepted" and "treated" by a JavaScript function.


Embedding JavaScript in HTML
JavaScript code is typically embedded into an HTML document using the SCRIPT tag. A JS code embedded can contain variable declarations, JS statements and JS functions.
The ways to embed JavaScript in HTML are described below :

JavaScript Runtime Environment
As it was described in the 'What is JavaScript' introductory section, a JavaScript program is usually part of an HTML document, which is itself displayed inside a browser window.
Accessing Display Objects
There are two ways in which a JavaScript program can interact with the display objects represented (by HTML elements) in an HTML document: a legacy JavaScript/HTML way, and a modern JavaScript/DOM way.
Simple User Interface functions
Several simple, text-based user interface pop-up windows can be activated, and used, from JavaScript using the methods of the 'window' object described below. Each of these methods halt the program execution until the pop-up window gets closed. Note: a JavaScript runtime environemnt (e.g. a console interpreter) may, or may not, provide these functions, depending on wether or not it implements a "virtual" 'window' object, which in turn is the object that must ultimately provide these methods. However, if a JavaScript program runs as part of an HTML document inside a browser window, then the 'window' object will always be available (and it will represent the browser window itself) and these methods will be available.


Events
An event is an action that occurs usually as a result of somthing the user/browser does. For example, clicking a button in a webpage, moving the mouse over a hyperlink, are events.
Actions that produce events can be of two categories:
Event handlers
If an event applies to an HTML tag (e.g. the mouse pointer is braught over an 'image' element, or the text contained inside a 'paragraph' element is clicked, or a button is clicked, etc), then an event handler code (a.k.a. event handler) can be defined for "capturing the event". The event handler code is a sequence of one or more JavaScript instructions, possibly including function calls, that receives control every time the corresponding event occurs.

The name of an event handler is the name of the event, preceded by "on" (e.g. the event handler name for the click event is 'onClick'). The list of possible events (e.g. 'click', 'mouseover', etc) is subject to a standardization process at the time of writing this document, and thus the event list contains some differences among various browser implementation (e.g. MSIE events and Firefox events are generally very similar, but differences do exist between the two browsers).


Event handler list
The following table presents the list of DOM's event handlers, and for each event handler the list of the browser object types for which the event handler is applicable.
The way to add an event handler (i.e. the JavaScript code) to a certain browser object is to add the event handler as an attribute to the corresponding HTML element.
Event handler Applies to
(Browser object types)
Occurs when
onAbort image Occurs when the loading of an image process is aborted(for example when the user clicks on a link or on the 'Stop' button).
onFocus body, frameset, anchor, area, input, select, textarea, button Occurs when an display object receives focus. It may be used with the same browser objects as onBlur event handler.
onBlur body, frameset, anchor, area, input, select, textarea, button Occurs when the focus to the one of display object listed before is removed.
onResize Most of the elements that have a specifieble size (i.e. for which 'height' and 'width' can be defined) Occurs when a resizable element changes its size.
onClick the most of browser object types Occurs when the mouse device button is clicked over an display object.
onChange body, input, select, textarea Occurs when a display object of 'form control' type loses the focus and its value has been modified since gaining focus.
onDblclick the most of browser object types Occurs when the mouse device button is double-clicked over an display object.
onKeydown the most of browser object types Occurs when a keyboard key is pressed down over an display object.
onKeypress the most of browser object types Occurs when a keyboard key is pressed and released over an display object.
onKeyup the most of browser object types Occurs when a keyboard key is released over an display object.
onLoad body, frameset, image
Occurs when the browser finishes loading an image, an HTML document, or all the frames within a frameset.
onUnload body, frameset Occurs when the browser removes an HTML document view or frame from a browser window.
onMouseout the most of browser object types Occurs when the mouse device is moved away from an display object.
onMouseover the most of browser object types Occurs when the mouse device is moved over an display object.
onMousedown the most of browser object types Occurs when the mouse device button is pressed over an display object.
onMouseup the most of browser object types Occurs when the mouse device button is released over an display object.
onMousemove the most of browser object types Occurs when the mouse device is moved while it is over an display object.
onReset only to the form object Occurs when a form display object is reseted(when the user clicks the 'Reset' button).
onScroll any scrollable container
e.g. window, iframe

Note: by using CSS one can create other scrollable containers apart from iframes
Occurs when the documentin a container element is scrolled.
Note: this event cannot be attached directly in HTML to a window/frame; instead, a javascript function must explicitly attach it via e.g.: window.onScroll=scrollHandlerFunctionName();
onSelect input-text, input-password, textarea Occurs when the user selects some text in a text field display object.
onSubmit only to the form object Occurs when a form display object is submitted(when the user clicks the 'Submit' button).

Some of the events described above (e.g. onFocus, onBlur, onResize) can also be attached to a 'window' or 'frame' object:
 <script>
// eventHandlerFunction is a reference to the function that treats the event occurrence
windowObjectReference.eventHandlerName = "eventHandlerCode";
</script>


Event Object
An Event object is created automatically by JavaScript on the occurrence of an event. The Event object has various properties that provide information about the event such as event type, the position of the cursor at the time the event occurred , etc.
The Event object model is implemented differently in IE and NS/Firefox :
Event bubbling
If an event occurs in conjunction with an HTML element that is contained inside another element (in the HTML containment hierarchy), then that event will trigger all the event handlers that are set for both the HTML element where the event occured, and also for all the HTML elements that contain the element that triggered the event: this process is referred to as the bubbling stage of the event. The order in which the event handlers are trigered is staring from HTML element on which the event occured, and incrementally continues up on the containment hierarchy. The 'event' object is always generated by the element which generated the event, while the 'this' pointer (passed from HTML) references the object to which each event handler is associated.

The following two examples illustrate how an event "bubbles" up the containment hierarchy, and what the 'event' object and the 'this' pointer are in such scenarios:
Timer methods
The 'window' object inside which a JavaScript program runs has a "hidden clock" object that can be used to schedule the execution of a JavaScript code sequence based on time intervals or delays. The scheduling mechanism relies on the following window object's methods:
Note: a JavaScript runtime environemnt (e.g. a console interpreter) may, or may not, provide these functions, depending on wether or not it implements a "virtual" 'window' object, which in turn is the object that must ultimately provide these methods. However, if a JavaScript program runs as part of an HTML document inside a browser window, these methods are available.


Simple JavaScript code debugging

The simplest way to debug a JavaScript program when no specialized development environment is available is to place a combination of "breakpoints" and "tracing messages" throughout the code: