[ Lexical Structure ]... [ Data Types ]...
[ Variables, Objects, Arrays, Statements ]...
[ Commenting in JavaScript ]...
[ Client-side JavaScript and the DOM ]
- JavaScript is case-sensitive.
- In most cases, JavaScript ignores white space such as tabs or spaces. However, JavaScript interprets a line break as the end of a statement (see below).
- A semicolon (;) signals the end of a JavaScript statement. You can omit the semicolon if each individual statement is on a separate line, but this is not good programming practice.
- You cannot use reserved words as identifiers. See JavaScript: The Definitive Guide for a list of reserved words.
- Numbers can be integers or floating-point literals. JavaScript makes no distinction between the two.
- A String is any text (letters, numbers, etc.) enclosed within single or double quote marks.
- Boolean data types have only two possible values: true and false.
Variables are used to reference values by an identifier.
- Use the var keyword to declare and initialize a variable.
- Variables are untyped, meaning that you can assign a variable a number value, and then later assign it a string value.
- Variables can be either local, defined only within a certain function, or global in scope.
An object is a collection of related pieces of data stored as properties of the object. Core JavaScript and client-side JavaScript include many built-in objects, such as the Date object and the objects associated with the browser itself. Functions associated with specific object properties are referred to as methods.
Arrays are similar to objects, but rather than having named properties, arrays contain numbered elements. Individual elements in an array may be referenced by its number, or index. Remember that index numbers begin with zero (0).
A statement is any collection of variables and operators that produce a value. JavaScript includes several complex statements that evaluate based on conditions and loops. They include:
- if..else: if a condition is true, a set of statements is executed. If the condition is false, other statements are executed.
- switch: a switch statement takes an expression, matches it to a case label, and executes the appropriate statement.
- for: a loop that repeats until the condition evaluates to false.
- do..while: a loop that executes once and continues to execute while a condition is true.
- while: a loop that executes as long as the condition is true.
JavaScript supports two types of comments: C style comments (//) for single lines and C++ style comments (/*...*/) for multi-line comments.
// The is a single line comment
/* This is a comment that
spans multiple lines */
In addition, JavaScript recognizes the opening HTML comment sequence (<!-- ) and treats it as a single line comment. However it does not recognize the closing sequence (-->). HTML comments should only be used within <script> tags to hide JavaScript from older browsers that do not recognize the SCRIPT element.
<script language="JavaScript">
<!--
statements here
// -->
</script>
Note that since JavaScript does not recognize the closing HTML comment sequence, a JavaScript comment (//) is added to prevent the browser from interpreting it as a JavaScript statement.
While core JavaScript refers to the structure of the language itself, client-side JavaScript refers to the core language as it applies to a specific client interpreter, in most cases a Web browser. Netscape, Internet Explorer, Opera and other browsers come with built-in JavaScript interpreters so that they can process JavaScript statements. These interpreters also allow scripts to reference the browser's Document Object Model (DOM) in order to respond to user events and dynamically alter content. The DOM is a tree-like organization structure that represents every element on a Web page, from windows and frames to form field values and style properties. Since each browser has its own DOM, the ways in which you implement JavaScript applications can vary quite a bit depending on the browser make and version number.
There are several different levels or versions of the DOM: DOM level 0 is the original browser Document Object Model developed by Netscape, and is supported by all major browsers. This level describes the basic hierarchical structure of a browser window, including windows, frames, documents, images, forms, etc.
DOM Level 1 was the W3C's first standardized version of the DOM, and it defines certain core features that allow access to nodes, elements, and attributes on a page. DOM level 2 is an extension of this standard which allows for interfacing with events, style sheets, and various types of documents. Newer versions of the popular browsers (Netscape 6 and IE 5, 5.5, and 6) support DOM levels 1 and 2 to varying degrees.
In addition, there is an intermediate DOM version between levels 0 and 1: the DOMs supported by version 4 Netscape and Internet Explorer. This DOM provides ways to interface with CSS elements, and is thus the first Document Object Model to support DHTML. However, Netscape 4.x and IE 4 have highly divergent DOMs and many browser compatibility issues may arise when coding for this generation of browser.
Online resources:
Netscape's DOM Developer Central
Microsoft's DOM Overview
DOM Level 2 Core Specification
[ The Window Object ]... [ frames[ ] array ]...
[ The Location Object ]...
[ Window methods ]...
[ The Screen Object ]...
[ Window Examples ]...
The Window object is the root object in the browser's DOM, and refers to a browser window or frame. In client-side JavaScript, the Window object is a global variable, meaning that in most cases you do not have to explicitly refer to it when calling methods, objects, or properties. For instance, you can call the alert() method without referencing the Window object (window.alert()).
If a window contains frames, these frames are accessible via the frames[ ] array. Each frame within a window may be referenced via its array index, or by its name as assigned within the <frame> tag. When referencing frames, the window that contains the frames is called the parent.
// the location property of a parent window
parent.location.href
// the background color of the second child frame
parent.frames[1].document.bgColor
Each window also contains a length property that lists the number of frames contained within the window. If the window does not contain any frames, the value of the window.length property is zero. (Note: this value is also stored in the window.frames.length property).
The Location Object contains a reference to the URL of the current document. The href property of the Location Object contains this same complete string, while other properties, such as protocol and pathname, return specific parts of the total URL.
The location property of a window is a read/write string, meaning you can assign it a value to cause a new page to load into a browser or frame window. If you want to overwrite the current URL in the browser's history, use the location.replace() method, supported in JavaScript versions 1.1 and higher:
location.replace("../new_page.html");
There are several portable methods associated with the Window object, including three simple dialog boxes. These methods are all modal--the script stops executing until a response is received from the user.
- alert(): issues a text message and a button to dismiss the dialog box
- confirm(): allows the user to proceed or cancel an action
- prompt(): prompts the user for a response.
The window.open() method is used to open a new browser window, and can take several optional arguments, including an URL, a name, and a list of features. If you do not include any features when creating the window, all features are included. If however, you include at least one feature, only the features listed appear in the window. Features are included as name=value pairs, where the value is either yes or no. However you can simply use the name of the feature without the "=value". The exceptions are the height and width features, which must include a pixel value if included.
Common features include:
- width: the width of the window in pixels
- height: the height of the window in pixels
- location: the browser's address bar
- menubar: the browser bar containing "File", "Edit, "View", etc.
- toolbar: browser buttons including "Back", "Forward", "Refresh/Reload", etc.
- scrollbars: enables or disables scrollbars.
- resizable: whether the user can resize the window by dragging its border.
- top: Y-coordinate in px of the window. IE.
- left: X-coordinate in px of the window. IE.
- screenX: X-coordinate in px of the window. Nav 4.
- screenY: Y-coordinate in px of the window. Nav 4.
The following script would open a window called "newWin" that is 600 x 400 px and includes a location bar but no other features:
window.open('http://www.mysite.com','newWin','width=600,height=400,location');
- window.close()/self.close(): closes windows created via JavaScript.
- window.focus(): brings keyboard focus to a window (returns window to top of the stack) JS 1.1
- window.blur(): remove keyboard focus (sends window back) JS 1.1
- window.resizeBy(h,v): resize the window by horizontal and vertical pixel amounts. JS 1.2
- window.resizeTo(h,w): resize the window to specified height and width. JS 1.2
- window.moveBy(h,v): moves the window relative to its current position. JS 1.2
- window.moveTo(x,y): move the window to the specified x,y coordinates. JS 1.2
- window.setTimeout(expression, msec): evaluates an expression or function once a number of milliseconds has elapsed.
- window.clearTimeout(timeoutID): clears an action called by setTimeout.
- window.setInterval(expression, msec): evalues an expression or calls a function every time a number of milliseconds has elapsed. JS 1.2
- window.clearInterval(clearIntervalID): clears an action called by setInterval. JS 1.2
Available in JavaScript 1.2, the Screen object contains information about the user's screen. Properties include:
- screen.availHeight: height of the display, not including platform-specific space for toolbars and task menus
- screen.availWidth: width of the display, not including platform-specific space for toolbars and task menus
- screen.height: total height of the screen
- screen.width: total width of the screen
Positioning Windows: top left bottom right middle source code
Time delay: setTimeout setInterval source code
Moving windows: start stop source code
Each Window object has a document property that represents the HTML document of the window or frame. The window.document property, or the Document object, in turn contains several properties and methods of its own, and provides access to all of the elements on a page.
[ Common Document Properties ]... [ Document Methods ]...
Note: These property identifiers are case-sensitive.
- linkColor, alinkColor, vlinkColor: these properties may be assigned within the head of the document. Values may either be standard color names or hexadecimal values.
- fgColor: the text color of a document.
- bgColor: the background color of a document.
- lastModified: a read only string that contains the date the document was last updated. This value is generated by the server.
- cookie: the document.cookie property allows you to read and write cookies.
- forms[]: an array of Form objects contained on the page.
- images[]: an array of Image objects contained on the page.
- all[]: (Internet Explorer 4) an array of every element in a document.
- layers[]: (Netscape 4) an array of layers contained on a page.
The Document object contains four methods that can be used to dynamically generate text and HTML.
- document.open() - explicitly creates a new HTML document to write to.
- document.write() - outputs the arguments enclosed within the parentheses.
- document.writeln() - the equivalent of document.write() except that it appends a newline after the final argument.
- document.close() - closes the output stream.
By using document.open(), document.write(), and document.close(), you can write HTML and variable values to the current page as well as to other windows and frames you create.
var header = "<html><head><title></title></head><body>";
var footer = "</body></html>";
parent.frames[0].document.open();
parent.frames[0].document.write(parent.header);
parent.frames[0].document.write("Output this text to the first frame.");
parent.frames[0].document.write(parent.footer);
parent.frames[0].document.close();
Since each frame is a window that contains its own Document object, you must reference the name or index of the frame before calling the document methods.
Write to a window A source code
Write to a window B source code
Write to frames source code
The Document object contains the images[] property, an array which stores references to all of the Image objects on a page. Each Image object has a read/write src property, meaning that you can use JavaScript to dynamically change the src of an image. Since images are stored in an array, you can reference them by their index:
// the 6th image on the page, referenced by its index
document.images[5].src
If you assign a name to an image via the <img> tag's name attribute, this image is stored as a property of the Document object and can be referenced by name:
// where imageName is a property identifier of the Document object
document.imageName.src
//where imageName is a string
document["imageName"].src
This last example illustrates the way in objects can behave as associative arrays. Unlike identifiers referenced in object properties, array strings can be dynamically manipulated.
In addition to referencing pre-existing objects, you can use JavaScript to create new Image objects with the new Image() constructor. You do not have to pass any arguments to the constructor, although there are two optional arguments-- width and height-- that you can pass to set the dimensions of a new image.
// creates the new image
image1 = new Image();
// sets the image's src property
image1.src = "images/home.gif";
The new Image() constructor does not cause the image to be rendered on the page; it only loads the image into the browser's cache.
The eval() function evaluates strings and expressions and is not associated with any particular object. This function is often used to dynamically alter the src property of images in an array.
eval(imageName + "on.src");
In this example the eval() function first evaluates the argument 'imageName', then appends it to a string.
|