Javascript Notes
Javascript Notes
primitive data types and their operators and expressions, screen output and keyboard input, controlstatements,
objects and constructors, arrays, functions, and pattern matching. The core is the heart of the language, including its
operators, expressions,statements, and subprograms. Client-side JavaScript is a collection of objects that support the control
of a browser and interactions with users. JavaScript, an XHTML document can be made to be responsive to user inputs such
as mouse clicks and keyboard use. Server-side JavaScript is a collection of objectsthat make the language useful on a Web
server—for example, to support communication with a database management system. Server-side JavaScript is used far
lessfrequently than client-side JavaScript
The original goal of JavaScript was to provide programming capability at both the server and the client ends of a Web
connection.
Client-side JavaScript can serve as an alternative for some of what is done with server-side programming, in which
computational capability resides on the server and is requested by the client. Because client-side JavaScript is embedded in
XHTML documents (either physically or logically) and is interpreted by the browser, thistransfer of load from the often
overloaded server to the often underloaded client can obviously benefit other clients. Client-side JavaScript cannot replace all
server-sidecomputing, however. In particular, although server-side software supports file operations, database access, and
networking, client-side JavaScript supports none ofthese. Interactions with users through form elements, such as buttons and
menus, can be conveniently described in JavaScript. Because button clicks and mouse movements are easily detected with
JavaScript, they can be used to trigger computations and provide feedback to the user
JavaScript Objects
In JavaScript, objects are collections of properties, which correspond to the members of classes in Java and C++. Each
property is either a data property or a function or method property. Data properties appear in two categories: primitive values
and references to other objects. (In JavaScript, variables that refer to objects are oftencalled objects rather than references.)
Sometimes we will refer to the data properties simply as properties; we often refer to the method properties simply as methods
orfunctions. We prefer to call subprograms that are called through objects methods and subprograms that are not called
through objects functions.
The type attribute of <script> must be set to “text/javascript”. The JavaScript script can be indirectly embedded in an
XHTML document with the src attribute of a <script> tag, whose value is the name of a file that contains the script—for
example,
The primitive data types, operations, and expressions of JavaScript are similar to those of other common programming
languages. Therefore, our discussion of them isbrief.
references the smallest representable number on the computer being used.Any arithmetic operation that results in an
error (e.g., division by zero) or that produces a value that cannot be represented as a double-precision floating-pointnumber,
such as a number that is too large (an overflow), returns the value “not a number,” which is displayed as NaN. If NaN is
compared for equality against anynumber, the comparison fails. Surprisingly, in a comparison, NaN is not equal to itself. To
determine whether a variable has the NaN value, the predefined predicatefunction isNaN() must be used. For example, if the
variable a has the NaN value, isNaN(a) returns true.The Number object has a method, toString, which it inherits from
Object but overrides. The toString method converts the number through which itis called to a string. Because numeric
primitives and Number objects are always coerced to the other when necessary, toString can be called through a
numericprimitive, as in the following code:
varstr = “George”;
varlen = str.length;
T h e typeof operator returns the type of its single operand. This operation is quite useful in some circumstances in a script.
typeof produces “number”,“string”, or “boolean” if the operand is of primitive type Number, String, or Boolean,
respectively. If the operand is an object or null, typeof produces“object”. This example illustrates a fundamental
characteristic of JavaScript: Objects do not have types. If the operand is a variable that has not been assigned avalue, typeof
produces “undefined”, reflecting the fact that variables themselves are not typed. Notice that the typeof operator always
returns a string. Theoperand for typeof can be placed in parentheses, making it appear to be a function. Therefore, typeof x
and typeof(x) are equivalent.
4.4.13 Assignment Statements
The assignment statement in JavaScript is exactly like the assignment statement in other common C-based programming
languages. There is a simple assignmentoperator, denoted by =, and a host of compound assignment operators, such as +=
and /=. For example, the statement
a += 7;
means the same as
a = a + 7;
In considering assignment statements, it is important to remember that JavaScript has two kinds of values: primitives and
objects. A variable can refer to aprimitive value, such as the number 17, or an object, as shown in Figure 4.1. Objects are
allocated on the heap, and variables that refer to them are essentiallyreference variables. When used to refer to an object, a
variable stores an address only. Therefore, assigning the address of an object to a variable is fundamentallydifferent from
assigning a primitive value to a variable.
A Date object is created with the new operator and the Date constructor, which has several forms. Because we focus on uses
of the current date and time, weuse only the simplest Date constructor, which takes no parameters and builds an object with
the current date and time for its properties. For example, we might have
The date and time properties of a Date object are in two forms: local and Coordinated Universal Time (UTC, which was
formerly named Greenwich MeanTime). We deal only with local time in this section.
Objects are often created with a new expression, which must include a call to a constructor method. The constructor that is
called in the new expression creates theproperties that characterize the new object. In an object-oriented language such as
Java, the new operator creates a particular object, meaning an object with a type anda specific collection of members. Thus, in
Java, the constructor initializes members but does not create them. In JavaScript, however, the new operator creates a
blankobject—that is, one with no properties. Furthermore, JavaScript objects do not have types. The constructor both creates
and initializes the properties.
The following statement creates an object that has no properties:
varmy_object = new Object();
4.8 Arrays
In JavaScript, arrays are objects that have some special functionality. Array elements can be primitive values or references to
other objects, including other arrays.JavaScript arrays have dynamic lengths.
4.9 Functions
JavaScript functions are similar to those of other C-based languages, such as C and C++.
4.9.1 Fundamentals
A function definition consists of the function’s header and a compound statement that describes the actions of the function.
This compound statement is called the bodyof the function. A function header consists of the reserved word function, the
function’s name, and a parenthesized list of parameters if there are any. Theparentheses are required even if there are no
parameters.
A return statement returns control from the function in which it appears to the function’s caller. Optionally, it includes an
expression, whose value is returnedto the caller. A function body may include one or more return statements. If there are no
return statements in a function or if the specific return that isexecuted does not include an expression, the value returned is
undefined. This is also the case if execution reaches the end of the function body without executing
fun1();
result = fun2();
JavaScript functions are objects, so variables that reference them can be treated as are other object references—they can be
passed as parameters, be assigned toother variables, and be the elements of an array. The following example is illustrative:
The scope of a variable is the range of statements over which it is visible. When JavaScript is embedded in an XHTML
document, the scope of a variable is the rangeof lines of the document over which the variable is visible.A variable that is not
declared with a var statement is implicitly declared by the JavaScript interpreter at the time it is first encountered in the script.
Variables thatare implicitly declared have global scope—that is, they are visible in the entire XHTML document (or entire file if
the script is in its own file)—even if the implicitdeclaration occurs within a function definition. Variables that are explicitly
declared outside function definitions also have global scope. As stated earlier, werecommend that all variables be explicitly
declared.
4.11 Constructors
JavaScript constructors are special methods that create and initialize the properties of newly created objects. Every new
expression must include a call to a constructorwhose name is the same as that of the object being created. As you saw in
Section 4.8, for example, the constructor for arrays is named Array. Constructors areactually called by the new operator,
which immediately precedes them in the new expression.Obviously, a constructor must be able to reference the object on
which it is to operate. JavaScript has a predefined reference variable for this purpose, namedthis. When the constructor is
called, this is a reference to the newly created object. The this variable is used to construct and initialize the properties of
theobject. For example, the constructor
CHAPTER 6
DYNAMIC DOCUMENTS WITH JAVASCRIPT
6.1 INTRODUCTION
6.2 POSITIONING ELEMENTS
6.3 MOVING ELEMENTS
6.4 ELEMENT VISIBILITY
6.5 CHANGING COLORS AND FONTS
6.6 DYNAMIC CONTENT
6.7 STACKING ELEMENTS
6.8 LOCATING THE MOUSE CURSOR
6.9 REACTING TO A MOUSE CLICK
6.10 SLOW MOVEMENT OF ELEMENTS
6.11 DRAGGING AND DROPPING ELEMENTS
Dynamic XHTML is not a new markup language. It is a collection of technologies that allows dynamic changes to documents
defined with XHTML. Specifically, a dynamic XHTML document is an XHTML document whose tag attributes, tag contents, or
element style properties can be changed by user interaction or the occurrence of a browser event after the document has
been, and is still being, displayed. Such changes can be made with an embedded script that accesses the elements of the
document as objects in the associated DOM structure.
Positioning Elements
It provides the means not only to position any element anywhere in the display of a document, but also to movean element to a
new position in the display dynamically, using JavaScript to change the positioning style properties of the elementThe
absolute value is specified for position when the element is to be placed at a specific place in the document display without
regard to the positions of
other elements. For example, if a paragraph of text is to appear 100 pixels from the left edge and 200 pixels from the top of the
display window, the following elementcould be used:
Relative Positioning
An element that has the position property set to relative, but does not specify top and left property values, is
placed in the document as if the position attribute were not set at all. However, such an element can be moved later. If the
top and left properties are given values, they displace the element by the specified amount from the position where it would
have been placed (if top and left had not been set). For example, suppose that two buttons are placed in a document and the
position attribute has its default value, which is static. Then the buttons would appear next to each other in a row,
assuming that the current row has sufficient horizontal space for them.it can be used to create superscripts and subscripts by
placing the values to be raised or lowered in <span> tags and displacing them from their regular positions.
6.2.3 Static Positioning
The default value for the position property is static. A statically positioned element is placed in the document as if it had
the position value of relative but no values for top or left were given. The difference is that a statically positioned
element cannot have its top or left properties initially set or changed later. Therefore, a statically placed element cannot be
displaced from its normal position and cannot be moved from that position later.
6.3 Moving Elements
As stated previously, an XHTML element whose position property is set to either absolute or relative can be moved.
Moving an element is simple: Changing the top or left property values causes the element to move on the display. If its
position is set to absolute, the element moves to the new values of top and left; if its position is set to relative, it
moves from its original position by distances given by the new values of top and left. In the next example, an image is
absolutely positioned in the display. The document includes two text boxes, labeled x coordinate and y coordinate,
respectively. The user can enter new values for the left and top properties of the image in these boxes. When the button
labeled Move It is pressed, the values ofthe left and top properties of the image are changed to the given values, and the
element is moved to its new position.A JavaScript function, stored in a separate file, is used to change the values of left and
top in this example. Although it is not necessary here, the id of the element to be moved is sent to the function that does the
moving, just to illustrate that the function could be used on any number of different elements. The values of the two text boxes
are also sent to the function as parameters. The actual parameter values are the DOM addresses of the text boxes, with the
valueattribute attached, which provides the complete DOM addresses of the text box values. Notice that style is attached to
the DOM address of the image to be moved becausetop and left are style properties. Because the input top and left values
from the text boxes are just string representations of numbers, but the top and left properties must end with some unit
abbreviation, the event handler catenates“px” to each value before assigning it to the top and left properties. This
document, called mover.html, and the associated JavaScript file, mover.js, are as follows:
Dynamic changes to colors are relatively simple. In the next example, the user is presented with two text boxes into which
color specifications can be typed—one for the document background color and one for the foreground color. The colors can
be specified in any of the three ways that color properties can be given in CSS. A JavaScript function that is called whenever
one of the text boxes is changed makes the change in the document’s appropriate color property: back-groundColoro
rcolor. The first of the two parameters to the function specifies whether the new color is for the background or foreground;
the second specifies the new color.The new color is the value property of the text box that was changed by the user. In this
example, the calls to the handler functions are in the XHTML text box elements. This approach allows a simple way to
reference the element’s DOM address. The JavaScript this variable in this situation is a reference to the object that represents
the element in which it is referenced. A reference to such an object isits DOM address. Therefore, in a text element, the value of
this is the DOM address of the text element. So, in the example, this.value is used as an actual parameter to the handler
function. Because the call is in an input element, this.value is the DOM address of the value of the input element. This
document, called dynColors.html, and the associated JavaScript file are as follows:
6.5.2 Changing Fonts
Web users are accustomed to having links in documents change color when the cursor is placed over them. Use of the
mouseover event to trigger a JavaScript event handler allows us to change any property of any element in a document,
including text, when the mouse cursor is placed over it. Thus, the font style and font size, as well as the color and background
color of text, can be changed when the cursor is placed over the text. The text can be changed back to its original form when
an event handler is triggered with the mouseout event. For CSS attribute names that are single words without hyphens, the
associated JavaScript property names are the same as the attribute names. But when an attribute name includes a hyphen, as
in font-size, the associated property name must be different (because a property name cannot include a hyphen). The
convention is that when an attribute name has a hyphen, the hyphen is deleted and the letter that follows is capitalized in its
associated property name. So, the property name associated with the attribute font-size is fontSize.
6.7 Stacking Elements
The top and left properties allow the placement of an element anywhere in the two dimensions of the display of a document.
Although the display is restricted to two physical dimensions, the effect of a third dimension is possible through the simple
concept of stacked elements, such as that used to stack windows in graphical user interfaces. Although multiple elements can
occupy the same space in the document, one is considered to be on top and is displayed. The top element hides the parts of
the lower elements on which it is superimposed. The placement of elements in this third dimension is controlled by the z-
index attribute of the element. Anelement whose z-index is greater than that of an element in the same space will be
displayed over the other element, effectively hiding the element with the smaller z-index value. The JavaScript style property
associated with the z-index attribute is zIndex.In the next example, three images are placed on the display so that they
overlap. In the XHTML description of this situation, each image tag includes an onclick attribute, which is used to trigger the
execution of a JavaScript handler function. First the function defines DOM addresses for the last top element and the new top
element. Then the function sets the zIndex value of the two elements so that the old top element has a value of 0 and the new
top element has the value 10, effectively putting it at the top. The script keeps track of which image is currently on top with the
global variable top, which is changed every time a new element is moved to the top with the toTop function. Note that the
zIndex value, as is the case with other properties, is a string. This document, called stacking.html
6.11 Dragging and Dropping Elements
One of the more powerful efects of event handling is allowing the user to drag and drop elements around the display screen.
The mouseup, mousedown, and mousemove events can be used to implement this feature. Changing the top and left
properties of an element, as seen earlier in the chapter, causes the element to move. To illustrate drag and drop, an XHTML
document and a JavaScript file that creates a magnetic poetry system is developed, showing two static lines of a poem and
allowing the user to create the last two lines from a collection of movable words.