This document was uploaded by user and they confirmed that they have the permission to share
it. If you are author or own the copyright of this book, please report to us by using this DMCA
report form. Report DMCA
Overview
Download & View Introduction To Javascript as PDF for free.
Introduction to JavaScript for New Programmers Tutorial This tutorial contains only a portion of the material covered in WestLake’s hands-on JavaScript class. We have included the entire table of contents of the JavaScript workbook to give you a better feel for the contents of the full course.
WestLake Internet Training
Introduction to JavaScript for New Programmers Page 1
Table of Contents Table of Contents ................................................................................................... Introduction to JavaScript .................................................................................... What is JavaScript?............................................................................................................................................. Debugging JavaScript .........................................................................................................................................
How JavaScript Works.......................................................................................... JavaScript Objects .............................................................................................................................................. The JavaScript DOM .......................................................................................................................................... Accessing the Document Object’s Background Color.......................................................................................... Exercise 1: Building a JavaScript Color Picker.................................................................................................... A Possible Solution to Exercise 1........................................................................................................................
Invoking Methods .................................................................................................. Modal Dialog Methods of the window Object ..................................................................................................... Nesting Quotes ................................................................................................................................................... Executing Multiple Statements in JavaScript ....................................................................................................... Event Handlers of the Link Object ...................................................................................................................... Exercise 2: Modifying Your Color Picker to Display an Alert.............................................................................. A Possible Solution to Exercise 2........................................................................................................................
JavaScript Functions ............................................................................................. Writing a JavaScript Function ............................................................................................................................. Passing an Argument to a Function ..................................................................................................................... Concatenating Strings and Variables ................................................................................................................... Exercise 3: Modifying Your Color Picker to use Functions.................................................................................. A Possible Solution to Exercise 3........................................................................................................................
Introduction to Scalar Variables........................................................................... JavaScript Data................................................................................................................................................... Storing Information from a Prompt ..................................................................................................................... Exercise 4: Making Your Color Picker More Personal......................................................................................... A Possible Solution to Exercise 4........................................................................................................................
Calling Functions from other Functions............................................................... Exercise 5: Calling functions from within other functions.................................................................................... A Possible Solution to Exercise 5........................................................................................................................
Introduction to the If Conditional......................................................................... Exercise 6: Using an if Conditional ..................................................................................................................... A Possible Solution to Exercise 6........................................................................................................................
Storing a List of Variables in an Array ................................................................ Creating an Array ...............................................................................................................................................
WestLake Internet Training
Introduction to JavaScript for New Programmers Page 2
Exercise 7: Creating an Array ............................................................................................................................. A Possible Solution to Exercise 7........................................................................................................................
Working with Forms in JavaScript ...................................................................... Referring to Forms and Form Elements in Dot Syntax Notation........................................................................... The value Property.............................................................................................................................................. Advanced Form Handling: Making the Function More Portable........................................................................... A Possible Solution to Exercise 8........................................................................................................................
Working with Numbers ......................................................................................... Casting (Converting) Strings to Numbers using Number() ................................................................................... Comparing Numeric Data ................................................................................................................................... Exercise 9: Calculating the Sum of Two Numbers ............................................................................................... A Possible Solution to Exercise 9........................................................................................................................
More Event Handlers & Methods......................................................................... Event Handlers ................................................................................................................................................... Event Handlers for Text Fields............................................................................................................................ Event Methods.................................................................................................................................................... Exercise 10: Enhancing your Form...................................................................................................................... A Possible Solution to Exercise 10......................................................................................................................
Handling Radio Buttons and Checkboxes in JavaScript ..................................... Handling Radio Buttons...................................................................................................................................... Handling Checkboxes ......................................................................................................................................... Marking a Radio Button or Checkbox ................................................................................................................. Exercise 11: Testing Radio Buttons and Checkboxes ........................................................................................... A Possible Solution to Exercise 11......................................................................................................................
Loop Structures in JavaScript .............................................................................. Basic Arithmetic Operators................................................................................................................................. Loop Structures .................................................................................................................................................. Exercise 12: Processing a Visitor's Registration Form.......................................................................................... A Possible Solution to Exercise 12......................................................................................................................
The return Statement ............................................................................................ Using the return Statement to Validate Radio Buttons.......................................................................................... Exercise 13: Using the return Statement to Test Radio Buttons ............................................................................ A Possible Solution to Exercise 13......................................................................................................................
Storing JavaScript in an External File ................................................................. Exercise 14: Creating and referencing an external library for JavaScript code ...................................................... A Possible Solution to Exercise 14......................................................................................................................
Form Validation..................................................................................................... Validating Numeric Data .................................................................................................................................... The String Object and Form Validation............................................................................................................... The onSubmit Event Handler and Form Validation..............................................................................................
WestLake Internet Training
Introduction to JavaScript for New Programmers Page 3
Exercise 15: Validating a complex form ..............................................................................................................
Advanced Form Validation ................................................................................... A Possible Solution to Exercise 16......................................................................................................................
Working with the window Object ......................................................................... window.open() and window.close()..................................................................................................................... document.write() ................................................................................................................................................ document.close() ................................................................................................................................................ Focusing and Closing a Window ......................................................................................................................... Exercise 17: Building a Pop-up Window ............................................................................................................. A Possible Solution to Exercise 17......................................................................................................................
The Date Object in JavaScript .............................................................................. Getting Today’s Date as an Object ...................................................................................................................... Exercise 18: Displaying the Current Time ........................................................................................................... A Possible Solution to Exercise 18......................................................................................................................
The Location Object .............................................................................................. Exercise 19: Directing the Client to a Browser Site.............................................................................................. A Possible Solution to Exercise 19......................................................................................................................
The Navigator Object ............................................................................................ Exercise 20: Detecting the Browser..................................................................................................................... A Possible Solution to Exercise 20......................................................................................................................
Generating Status Bar Messages........................................................................... The window’s status Property ............................................................................................................................. Exercise 21: Displaying Status Bar Messages...................................................................................................... A Possible Solution to Exercise 21......................................................................................................................
Creating a Scrolling Status Bar Message ............................................................. The substring() Method of the string Object ........................................................................................................ Exercise 22: Creating a scrolling status bar message............................................................................................ A Possible Solution to Exercise 22......................................................................................................................
Working with Images ............................................................................................ Pre-loading Images ............................................................................................................................................. The eval() Method .............................................................................................................................................. Exercise 23: JavaScript Image Flipping............................................................................................................... A Possible Solution to Exercise 23......................................................................................................................
Creating a slide-show with Image Flipping ......................................................... Exercise 24: Creating a Slide Show ..................................................................................................................... A Possible Solution to Exercise 24:.....................................................................................................................
Appendix A: Color Values and their Hex Triplet Equivalents ........................... Appendix B: Recommended Resources ................................................................
WestLake Internet Training
Introduction to JavaScript for New Programmers Page 4
Introduction to JavaScript What is JavaScript? JavaScript is a scripting language developed by Netscape that gives Web authors the ability to design interactive sites. JavaScript interacts with HTML source code, providing a means to create dynamic content that reacts to user actions. Because JavaScript is an open source language, anyone can use the language without purchasing a license. With JavaScript, a Web page can react to what the user is doing. Images can swap when the mouse moves over them, form elements can influence each other on the fly, and calculations can be made without having to resort to a CGI script. In fact, a great deal can be accomplished with very little programming. There is no need for a fancy computer, complex software, or access to a Web server; all the work can be done and tested right on the local computer. JavaScript is used for: • Building self-validating forms. JavaScript enables intelligent, self-validating forms that instantaneously warn the user when the entered data is incorrect. Because client-side JavaScript is inline with HTML, the user is forewarned before the data is submitted to the server, saving both the user and the server time and resources. • Creating pages in which images change dynamically. JavaScript controls the source of an image, thereby allowing the designer to automatically swap images in response to the user’s actions. • Enabling dynamic calculations within forms. As the user fills out a form, calculations can automatically update based on the user’s input. For example, as the user checks products he wishes to order, JavaScript’s control of a field’s display instantaneously updates the total cost. • Opening and Closing Windows. JavaScript code can create new windows and display appropriate information in that new window. For example, when the user moves her mouse over a word, a small window with the word’s definition could appear, linger for 10 seconds, and then disappear. One common use of the pop-up window is to display ads, as America Online’s site does at http://www.aol.com. • Changing the displayed URL. JavaScript code can be used to change the URL displayed by a window or frame, without the user having to click on a hyperlink. This change could be triggered in response to selecting an item in a pull-down menu, as a result of a timer elapsing, or in response to some other action.
Client-side vs. Server-side JavaScript Client-side JavaScript, the topic of this course, refers to JavaScript code that is executed by the browser (client). Server-side JavaScript is also possible, which is scripting code that executes on the server. Netscape Web servers, if equipped with LiveWire Pro, support server-side applications written in JavaScript. Microsoft Internet Information Server (IIS) supports similar server-side JavaScript applications, called Active Server Pages.
What is the Difference Between a CGI Script and Client-side JavaScript? CGI (Common Gateway Interface) scripts are executed on the Web server (much like server-side JavaScript), whereas client-side JavaScript is executed within the browser. CGI scripts are better suited for completing tasks that require information to be stored on the server or exchanged over the network (e.g., with a database). On the other hand, client-side JavaScript is designed for simple tasks that do not require interaction with the server, and therefore can be executed instantaneously.
WestLake Internet Training
Introduction to JavaScript for New Programmers Page 5
JavaScript can handle many of the same responsibilities that a CGI script can manage; the benefit to using JavaScript is that it is executed on the client side and does not require further interaction with the server. For example, consider the following model of the client/server relationship:
http request
http response Browser/Client
Server
When a client makes a http: request (requests an HTML page) to the server, the server checks the url to verify that the file exists. If so, an http: response (an HTML page) is provided to the browser and the page displays in the client window. Otherwise, an error message saying the file could not be found results. Any JavaScript on the page downloads with the HTML.
Page with JavaScript
How cool is JavaScript
Once the page containing the client-side JavaScript loads in the browser, all actions are generated from the client’s browser. Further interaction with the server is not required until the user attempts to do something JavaScript cannot handle.
Page without JavaScript
submit
On a page that relies on CGI scripts, the action must be submitted to the server…
processed by the server… I’m pooped !
http: response
and once again returned to the browser.
WestLake Internet Training
Introduction to JavaScript for New Programmers Page 6
JavaScript and Java: What Do They Have in Common? Other than the letters “J-a-v-a” and the fact that both are executed by the browser, JavaScript and Java have very little in common. Whereas JavaScript is an interpreted language, Java is a compiled language. Most importantly, while JavaScript is primarily just a scripting enhancement to HTML, Java is a full-blown language that can be used for writing very complex applets and applications, making it much harder to learn and implement than JavaScript.
Which Browsers Support JavaScript? Like all Web technologies, JavaScript’s capabilities and support have evolved over time. The following chart describes which browsers support which versions of JavaScript:
Browser
JavaScript versions supported Other scripting
Netscape Navigator 2.0 Netscape Navigator 3.0 Netscape Communicator 4.0-4.05 Netscape Communicator 4.06+, 4.5 MS Internet Explorer 3.0 MS Internet Explorer 4.0
JavaScript 1.0, pieces of 1.1 JScript, VBScript* JavaScript 1.0, 1.1, pieces of JScript, VBScript 1.2
* JScript is Microsoft’s version of JavaScript. VBScript, a derivative of Visual Basic, is another client-side scripting language natively supported by Internet Explorer.
JavaScript 1.1 implements significant enhancements and corrections to the original release of JavaScript. JavaScript 1.2 breaks more new ground, with complete support for mouse and keyboard events, as well as the ability to manipulate cascading style sheets and layers. JavaScript 1.3 further enhances and corrects the language.
Debugging JavaScript Learning any language naturally entails making errors. Fortunately, there are tools available to help debug, locate and fix problems. At the simplest level, browsers have error messages that will help identify and alert you to your errors. In Netscape 4.x, an error console is available by typing javascript: into the address bar of the browser.
WestLake Internet Training
Introduction to JavaScript for New Programmers Page 7
This console pinpoints the JavaScript error. Microsoft Internet Explorer 5.0+ also provides error warnings, as indicated by the yellow error icon ( ) in the bottom left corner of the Browser window. To display the error, double click on the icon. The following JavaScript error console appears:
Although these debugging tools are useful to pinpoint the problem, they may not always lead to the needle in the haystack. Further exploration and troubleshooting may be required.
WestLake Internet Training
Introduction to JavaScript for New Programmers Page 8
How JavaScript Works JavaScript Objects JavaScript is referred to as an Object-based language, meaning that predefined objects exist within the JavaScript hierarchy. One object, for example, is the document object. This refers to the current HTML page that the client is viewing in the browser window. Using JavaScript, objects can be asked to change (perhaps in appearance) or perform a task. Modifying an object’s appearance entails accessing and changing a property; asking the object to perform a task entails invoking an object’s method. Every JavaScript object has associated properties and methods. A property is a characteristic that can be manipulated or changed about the object. For example, the document object has a background color. The background color (bgColor) is considered to be a property of the document object. A method, on the other hand, is an action that an object can perform. The document object can write content into the document via the write() method. So, JavaScript can change the characteristics of an object (via its properties) as well as ask an object to perform specific tasks (via its methods). In addition to properties and methods, JavaScript objects have event handlers that trigger the changes to occur. Different event handlers exist for different objects, and are treated as an attribute of the specific object. For example, some event handlers for a link include onClick, onMouseOver, and onMouseOut. As the course progresses, many of JavaScript objects (as well as their associated properties, methods, and event handlers) will be discussed in detail. As an example, consider the following button. Remember, the form’s button has no innate actions: Adding an event handler (followed by an action or set of actions) to the button can create a dynamic change of the page when that button is triggered: red is the new value of the background color
onClick is the event handler being added to the Button object. This event handler tells the actions when to execute.
document is the object that will be affected.
bgColor (the background color) is the property of the document that will change.
Notice that the button’s onClick event handler triggers the action, but that the action can then alter any of JavaScript’s objects.
WestLake Internet Training
Introduction to JavaScript for New Programmers Page 9
JavaScript Statements A statement is a command that the browser's JavaScript interpreter executes. Although not readily apparent, you have already encountered a statement in the previous example. The statement is the piece of code that is executed when the button is clicked. In the above example, the statement changes the document’s background color to red: document.bgColor='red'; Multiple statements can be assigned to the same event handler. Statements can perform a variety of tasks, including the following:
• Define or initialize a variable • Assign a value to a property or variable • Change the value of a property or variable • Invoke an object’s method • Invoke a function • Test a condition and make a decision
JavaScript Syntax Before looking at JavaScript objects in more detail, it is important to become familiar with the rules of syntax. JavaScript’s syntax is modeled after programming languages such as Java and C++. Some basic syntax guidelines follow:
• JavaScript is case-sensitive. • JavaScript statements are separated by semi-colons. • Whitespace is ignored, so spaces, tabs, and new-lines can be used to indent the code to your liking. It is important, however, to ensure there are no spaces between a method and its parentheses. Also, do not break a statement across two lines if the first line is long enough to hold the entire statement, as this will result in JavaScript errors. • Any literal value (such as a text string) must be put in a set of quotes. In addition, multiple sets of quotes must be nested appropriately. • Certain keywords have been reserved in JavaScript for specific purposes. Keep this in mind as your knowledge of JavaScript increases. The following keywords have been reserved, and may not be used for anything other than their intended purpose. Reserved keywords include the following:
break case continue default delete do WestLake Internet Training
for function if import in new
this true typeof var void while
Introduction to JavaScript for New Programmers Page 10
else export false
null return switch
with
JavaScript also reserves some words for future versions of the language:
catch class const debugger
enum extends finally
super throw try
The JavaScript DOM JavaScript objects are related to each other through a hierarchy called a Document Object Model (DOM). The Document Object Model defines how objects can be called upon, and is specific to the individual browser that is executing the actions. As you already know, the JavaScript DOM relies on objects. Objects can have can have child objects. The child objects have their own set of properties and methods and can have child objects inside them as well. To access an object, simply provide the path to the desired object from the top of the hierarchy. The object hierarchy is built off a single base object, the window. The following outline illustrates the relationship between the window object and some of the objects it contains:
Partial JavaScript Object Hierarchy
window
document
history
anchors[]
forms[]
images[]
radio button set[]
textfield
checkbox
location
links[]
Accessing the appropriate object entails stepping down the object hierarchy by use of dot notation. Simply work your way through the hierarchy, placing a dot (a period) before each new child object that you reference. Notice that some of the objects are followed by brackets, indicating that there may be more than one of that type of object on the page. For example, the code to access an image follows: window.document.images[1]; More specifically, the above code references the second image in a page. The brackets at the end of the image object indicate the object is part of an array (a list). In this case, the array is a list of images in the document. The number in the brackets refers to the image’s placement (index) in the code. Because JavaScript starts counting with zero, the code for the first image listed in the html page would be as follows: window.document.images[0];
WestLake Internet Training
Introduction to JavaScript for New Programmers Page 11
and the JavaScript code to access the second image would be: window.document.images[1]; It is important to know that each browser and each browser version may have different Document Object Model hierarchies. Throughout most of this class, the hierarchy used is cross-browser compatible; however, as you further explore the JavaScript language, you will find that these different DOMs must be accounted for.
Naming Objects Although accessing an object can be done by the item's placement in the JavaScript array, doing so can be cumbersome. Instead, naming the object (by using the name attribute) provides a more intuitive means for referencing an object. Any html tag can be named via the name attribute. For example, the following code names an image chicken: So, instead of referencing the above image (the first image on the page) as: window.document.images[0]; the object can be referenced by its name, as provided by the name attribute. window.document.chicken; Providing names for objects makes accessing those objects through the DOM much more intuitive.
Accessing an Object’s Methods or Properties via the DOM Accessing an object’s properties and methods works via the Document Object Model as well. For example, to change the document’s background color property (bgColor) or write the words “Hello World” into the document via the write() method, the code would be as follows: window.document.bgColor='red'; window.document.write('Hello World'); Notice both properties and methods are simply appended to the end of the object’s name and separated from its parent by a period. However, notice the syntax differences between changing a property and invoking a method. To change a property, start by accessing the object, its property, and then set the property equal to a new value. All properties are set in this manner: window.document.bgColor='red'; A method, on the other hand can do something, and is always followed by a set of parentheses. If additional information for that method is needed, that additional information is contained in the parentheses. For example the code that writes “Hello World” into the document follows: window.document.write('Hello World'); Methods are always followed by a set of parentheses, regardless of whether those parentheses contain further parameters. Inside of the parentheses, any argument that is not a variable name or numerical value should be placed in quotes to indicate that it is a text string or string literal.
Built-In Objects in Navigator and (MSIE 3.0) JavaScript incorporates a number of built-in objects. The developer creates other objects as he codes his html page. The following tables explain the primary built-in objects in JavaScript:
Object navigator
Description
The navigator object provides properties that expose information about the current browser to JavaScript scripts.
WestLake Internet Training
Introduction to JavaScript for New Programmers Page 12
window
document
location history
The window object provides methods and properties for dealing with the actual browser window, including objects for each frame (if frames are used). The document object is one of the most commonly used objects in the hierarchy. It contains objects, properties, and methods for working with document elements including forms, links, anchors, and Java applets. The location object provides properties and methods for working with the currently open URL. The history object provides information about the history list and enables limited interaction with the list.
During this course, the window, document, and form objects will be discussed in detail.
Other built-in objects There are three other objects that are a part of the core JavaScript language and exist independent of the Document Object Model: String, Date, and Math.
Object String
Date
Math
Description The String object enables programs to work with and manipulate strings of text, including extracting substrings and converting text to uppercase or lowercase characters. The Date object allows programs to work with and manipulate the current date. The object includes methods for calculating the difference between two dates and working with times. The Math object allows programs to work with and manipulate numerical values generated by the Math object. For example, the Math object's properties and methods enable programmers to round numbers as well as generate random numbers.
Both the String and Date objects will be discussed in detail.
Accessing the Document Object’s Background Color As you have already seen, the background color of the document object can be changed with JavaScript. For an example, open docbgcolor.html. The following page will appear:
WestLake Internet Training
Introduction to JavaScript for New Programmers Page 13
When the button is clicked, the background color of the page changes to red. View the source of the page to see the following code: Background Color Change
JavaScript has been added to a button. When invoked by a click of the button, the code changes the background color. Notice that the event handler (onClick) is treated as if it is an attribute of the tag. The event handler is followed by an equal sign and a JavaScript statement nested in a set of quotes. The background color (document.bgColor) can be assigned any valid color name, or a hexadecimal RGB triplet. For a listing of valid colors and corresponding triplets, consult http://www.lynda.com/hexh.html.
WestLake Internet Training
Introduction to JavaScript for New Programmers Page 14
Exercise 1: Building a JavaScript Color Picker In this exercise, you will be constructing a JavaScript-based color picker. When complete, your page will appear as follows:
Clicking on each button changes the background of the page to the specified color. To complete this exercise:
1. From the JStutorial .zip file you downloaded, drag the icon for exercise1-temp.html to the Notepad icon on the Desktop. This will open the file in Notepad. 2. The exercise file appears as follows. Please complete the missing sections, as indicated by bold . Color Picker
WestLake Internet Training
Introduction to JavaScript for New Programmers Page 15
3. When finished, save the file. 4. Open the file in the browser and test each button. If there are errors, bring Notepad back to the foreground, edit the code, and save it. Then, bring the browser back to the foreground and reload the page. Repeat this step until all errors have been resolved.
If you are done early... • Add buttons for several additional colors to your page.
WestLake Internet Training
Introduction to JavaScript for New Programmers Page 16
A Possible Solution to Exercise 1 As contained in exercise1-done.html: Color Picker
WestLake Internet Training
Introduction to JavaScript for New Programmers Page 17
Invoking Methods The last exercise made dynamic changes to a page by accessing an object’s property and assigning that property a new value. Methods can also be invoked via the Document Object Model. Remember, a method belongs to a particular object and is always followed by a set of parentheses. If further parameters are needed for the method to complete, those parameters are set inside of the parentheses.
Modal Dialog Methods of the window Object The window object has three methods for displaying dialog messages: the alert(), prompt(), and confirm() methods. These dialog boxes communicate with the end user, and must be dealt with by the end user before he can move on. These dialogs are referred to as Modal Dialog Methods of the window object because they stay at the top of the window stack until the user clicks a button on the message to remove them. The current browser window cannot be opened over top of one of these three modal dialogs. For an example of each, open dialogs.html in a browser:
Clicking each of the buttons invokes the alert(), prompt(), and confirm() methods, respectively. The code for this page is as follows, and will be detailed further. Modal dialogs
alert() window.alert() displays a dialog with warning text and an OK button. The user must click OK before proceeding further with the page. The alert() method takes one parameter: the message to display. For an example, take a look at the JavaScript code for the alert() button's onClick event handler in dialogs.html: window.alert('Ouch');
The above code invokes the following alert box when the button is clicked:
prompt() window.prompt() displays a dialog that asks a question and provides a blank field for the user to fill in her answer. OK and Cancel buttons are provided, and one must be clicked before the user may continue. The window.prompt() method requires two parameters: the text for the message to display in the dialog and a default entry (if any) for the field to display. For demonstration, examine the following code: window.prompt('What is the name of your company?', 'WestLak e Internet Training'); When invoked, the above code displays the following prompt dialog box:
Notice that the words WestLake Internet Training automatically appear in the field for the user. This can also be left blank by leaving the set of quotes containing the second parameter empty: window.prompt('What is the name of your company?', '');
confirm() window.confirm() displays a message in a dialog box with both an OK and Cancel button. For example, the following code: confirm('Please press OK to cont inue'); WestLake Internet Training
Introduction to JavaScript for New Programmers Page 19
would display the following dialog when invoked:
The confirm() method requires only one parameter (the message that the dialog should display).
The window as the Implied Object Often, coders like to make their code as concise as possible. One way to do this is to strip off all references to the window object. Because the window is the topmost object in the hierarchy, it is automatically implied when the window’s properties, methods, or child objects are referenced. So, rather than coding: window.document.bgColor='red'; window.alert('Hello World'); you may opt to write: document.bgColor='red'; alert('Hello World');
Nesting Quotes The above examples of the window’s alert(), prompt(), and confirm() methods used single quotes inside the parentheses. However, in some cases double-quotes may have worked just as well. The key lies in how the code occurs in the page. For now, you only know how to invoke the code inline triggered by an object’s event handler (such as onClick): Notice how the onClick event handler is followed by an equal sign and a set of double-quotes. Quotes signify a set; the first double-quote is the start of the set until it reaches the next double-quote. Likewise, the first single quote is the part of a set until the second single quote appears. So, the following code: would be interpreted to run the “alert(” statement when the button was clicked. This statement is not valid JavaScript and would result in errors. As a result, be sure to nest sets of quotes appropriately so that faulty statements are not sent to the JavaScript interpreter.
WestLake Internet Training
Introduction to JavaScript for New Programmers Page 20
Executing Multiple Statements in JavaScript So far, the event handlers have been executing single JavaScript statements. To execute two or more JavaScript statements in succession, separate them by semi-colons (;). For example, clicking the following button: invokes two statements. The first statement changes the background color to red and the second displays an alert dialog. It is a good idea to end all JavaScript statements with a semi-colon in the event that you later want to add another statement. Take note that the order of the actions will execute based on the order they are placed in the script. Although most statements occur instantaneously, putting an alert() method first requires the user to click OK before any of the other statements are executed.
Event Handlers of the Link Object Thus far, the onClick event handler has been demonstrated on a button. This event handler also works with an anchor tag (or link): Linked Text Two other event handlers supported by the link object are onMouseOver (when the user first moves her mouse over the link) and onMouseOut (when the user moves her mouse off of the link). These event handlers are called upon just as the onClick event handler, each as its own attribute of the link tag. The onMouseOver and onMouseOut event handlers are often used with a link tag to dynamically change content as the user moves her mouse around the page. In the following example, the background color change is triggered by both the onMouseOver and onMouseOut events (mousemovements.html):
The code for the page is displayed below: Mouse MovementsChange Colors?
WestLake Internet Training
Introduction to JavaScript for New Programmers Page 21
Notice that the same object can have more than one event handler, and that each event handler is treated as a separate attribute of the object's tag.