JavaScript and the Document Object Model


The JavaScript programming language has had an important role in the evolution of the web since it was developed by Brendan Eich of Netscape and included in the Netscape Navigator 2 browser in late 1995. JavaScript’s core script syntax closely resembled Java, so it was named JavaScript when it was released, though it is otherwise unrelated to Java. JavaScript made client-side web applications possible; that is, JavaScript code could be embedded in web pages and would be interpreted by the web browser to do things such as process numbers and modify the contents of HTML forms. The way that JavaScript referenced HTML elements such as forms, links, and anchors as “children” of the document “object,” and the way that it handled form inputs as children of their parent form became known as the Document Object Model (DOM) level 0. The DOM, in short, is the specification for how objects in a web page (text, images, headers, links, etc.) are represented. The DOM defines what attributes are associated with each object, and how the objects and attributes can be exposed to scripts for access and manipulation.

In 1996, Netscape passed their JavaScript language to the European Computer Manufacturers Association (ECMA) for standardization. This resulted in the ECMAscript standard. As of 2006, the latest version of JavaScript is version 1.6, which is a superset of ECMAscript-262, Edition 3. JavaScript support in Microsoft’s Internet Explorer web browser is actually Microsoft’s own extension of JavaScript called JScript.

One major use of web-based JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of a web page to perform tasks not possible in HTML alone. Some common examples of JavaScript usage are the following:

  • Popping up a new web browser window with programmatic control over the size, position, and “look” of the new window. (Usually JavaScript is used to ensure that menus, toolbars, etc., are not visible on popped-up browser windows.) This usage of JavaScript is sometimes viewed as more of an annoyance than something useful, and web browser plug-ins such as “popup blockers” have sprouted to deal with JavaScript-generated pop-up windows.

  • Validating web form input values to make sure that they will be accepted before they are submitted to the web server.

  • Changing images as the mouse cursor moves over them, also known as a “mouse-over” effect. This effect is favored by some web page designers to draw a user’s attention to important links displayed as graphical elements. Much of this type of functionality can now be achieved-usually more easily-using Cascading Style Sheets, which will be discussed later in this chapter.

  • Inserting text and HTML tags dynamically into an HTML page.

  • Reacting to events. A JavaScript program can be set to execute when something happens, such as when a page has finished loading or when a user clicks an HTML form element such as a button.

JavaScript support has been a standard feature of most web browsers since the late 90s. JavaScript has gained in importance recently as part the AJAX web application development technique (see http://en.wikipedia.org/wiki/ΛJΛX). AJAX (the term is shorthand for Asynchronous JavaScript and XML) has been used to create high-profile web applications such as Google Maps (http://maps.google.com), which seem to be able to blur the distinction between web applications and desktop applications with their high level of interactivity.

Introduction to JavaScript Usage

JavaScript was designed to add interactivity to HTML pages. It is a lightweight scripting language that consists of lines of executable instructions, which are usually embedded directly into HTML pages; these instructions are executed when the HTML page is loaded by a web browser.

The HTML <script> tag is used to insert a JavaScript into an HTML page, as shown in the following example:

 <html> <body> <script type="text/javascript "> // JavaScript comments begin with double forward slashes as in C++ and Java. document.write( "Hello World!" ); </script> </body> </html>

An HTML file that consists of the preceding code will print Hello World! in the web browser window when loaded. In the preceding HTML file, the <script type=“text/ javascript”> and </script> tags determine where the JavaScript starts and ends. The only JavaScript instruction in this file, document.write, is a standard JavaScript command for directing output to a page, in this case the literal string “Hello World!”. The document.write instruction is also a simple example of JavaScript’s use of the resulting web page’s Level 0 DOM, in which the document in document.write is the HTML document object, and write is a built-in method of the document object, a method that “writes” output on the document. The semicolon at the end of lines of JavaScript such as document.write(“Hello World!”); is optional. As in C++ and Java, comments are started using two forward slashes (//).

The use of a variable in JavaScript is demonstrated in the next code fragment. JavaScript supports only three types of simple variables. These are text (string), numeric, and Boolean (true or false). In the example, the variable str_greeting is initially assigned the literal string “Hello World!”, so str_greeting is a string variable.

 <script type="text/javascript"> var str_greeting = "Hello World!"; document.write( str_greeting); </script>

If we wanted to embed the current date and time in the HTML document, we could use a built-in JavaScript function, Date(), as follows:

 <script type="text/javascript"> document.write( "The current date and time is " + Date()) </script>

The “+” operator in JavaScript, used in the preceding code, is designed to allow the easy concatenation of strings of text, such as “The current date and time is” + Date().

The following is another simple HTML file with an embedded JavaScript function. Each time this HTML file is loaded by a web browser, one of three image files will be randomly selected and displayed in the browser window using the HTML <img> tag:

 <html> <head>   <title>JavaScript function example #1</title>    <script type="text/javascript">    function display_image()    {       // Get a random integer between 0 and 2       var whichImg = Math.round(Math.random() * 2);       // Create a 3 element string array       var image = new Array(3)       // Assumes that the image files named below are in the same directory as       // this HTML document.       image[0] = "moose.png"       image[1] = "squirrel.png"       image[2] = "mountie.png"       document. write ( "<center><img src="/books/4/466/1/html/2/ + image [whichImg] + "></center>")    }    </script> </head> <body> <script type="text/javascript">    // Call the function that was defined in <head> section.    display_image() </script> </body> </html

As demonstrated in the preceding HTML file, JavaScripts that contain functions are usually placed in the <head> section of the HTML document to ensure that the script is loaded before the function is called. The function, display_image(), that was defined in the <head> section, is called unconditionally in the <body> section of the document each time the document is loaded. The example also demonstrates the use of the Math.round and Math. random JavaScript built-in functions to generate an appropriate random integer and also the creation and use of an array. You can see that the document.write( “<center><img src=” + image[whichImg]+“></center>”) statement contains in-line HTML tags to center the randomly selected image file on the rendered web page.

An interactive way to call a JavaScript is demonstrated in the following HTML file. This time, when an HTML form button is pressed by the user, one of three image files will be randomly selected and displayed in the browser window:

 <html> <head>   <title>JavaScript function example #2</title>   <script type="text/javascript">   function display_image()   {      var whichImg=Math.round(Math.random() * 2);      var image=new Array(3)      image[0]="moose.png"      image[1]="squirrel.png"      image[2]="mountie.png"      document. write ( "<center><img src="/books/4/466/1/html/2/+image [whichImg]+"></center>")   }   </script> </head> <body> <form>    <input type="button" onclick="javascript:display_image()"    value="Press to display random image"> </form> </body> </html

In the preceding example, the form button displayed in the browser window will have the text “Press to display random image” inside it. The onclick=“javascript:display_image()” instruction is an example of JavaScript being used to respond to a browser event.

JavaScript has the usual complement of arithmetic operators, comparison operators, logical operators, and program flow control structures that other high-level programming languages have. These operators and control structures are very much like their counterparts in C/C++ and Java, reflecting the syntactic heritage of JavaScript. The control structures include conditional selection structures such as if, if-else, if-else if-else, and switch. The control structures also include repetition structures (loops) such as for, while, and do-while. See http://en.wikipedia.org/wiki/JavaScript_syntax for a full JavaScript syntax reference.

The Document Object Model

As previously mentioned, the DOM exposes parts of an HTML document as objects to scripting languages such as JavaScript so that they can dynamically access and update the content, structure, and style of HTML documents. The DOM Level 0 is not a W3C recommendation but simply a way to refer to the early JavaScript DOM, which is still used. The DOM Level 1 has been a W3C recommendation since 1998 and is well supported by the major browsers today and is also language-independent. The DOM makes available a number of convenient methods and properties that web programmers can use in their scripts, whether written in JavaScript or other languages. The W3C’s DOM Level 1 reference can be found at http://www.w3.org/TR/REC-DOM-Level-1.




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net