Introduction To Javascript

  • November 2019
  • PDF

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.

More details

  • Words: 9,517
  • Pages: 42
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 JavaScript 1.0, 1.1 JavaScript 1.0, 1.1, 1.2 JavaScript 1.0, 1.1, 1.2, 1.3

languages

VBScript (with plug-in) VBScript (with plug-in) VBScript (with plug-in)

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:
This is my form:
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


value="Click here!" onClick="document.bgColor='red';">

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



WestLake Internet Training

Introduction to JavaScript for New Programmers Page 18



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 Movements Change 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.

NOTE

In the above code, the hypertext reference is set to a pound sign. This pound sign (without any following text) is one way to incorporate a dead link: a link that does not load a new page in the browser window.

Exercise 2: Modifying Your Color Picker to Display an Alert In this exercise you will modify the color picker to display alert dialogs after the background color changes. The alert statement should inform the user of the color change:

1. Open exercise2-temp.html in Notepad. This code has the same functionality of the code completed in the last exercise: Color Picker



WestLake Internet Training

Introduction to JavaScript for New Programmers Page 22



2. Add a JavaScript statement that invokes an alert message to each of the buttons. Remember to use the semi-colon to separate JavaScript statements. 3. Save the page and test each button in a browser . If one of your buttons does not work properly, fix the code as needed. Be sure to save and refresh the page to test the latest version.

If you are done early: • \n (the newline character) has the same effect within the text of dialogs that a
tag has within HTML. Experiment with breaking your dialog text across multiple lines. • Add a link with both onMouseOver and onMouseOut events. This link should be responsible for changing the background color when the mouse rolls over it, and changing the background color to white when the mouse rolls off.

WestLake Internet Training

Introduction to JavaScript for New Programmers Page 23

A Possible Solution to Exercise 2 As contained in exercise2-done.html: Color Picker



WestLake Internet Training

Introduction to JavaScript for New Programmers Page 24

JavaScript Functions The code in the last exercise was redundant, as the same actions were executed by clicking each button. Functions alleviate this redundancy. JavaScript functions are a stored set of statements that can be executed by any object's event handler in the page. When called upon, the function executes the statements it contains. Storing actions which will be called upon repeatedly within a function makes the code more concise, and reduces the risk of error. For example, consider the following demonstration, found in functions.html:

The code for this page follows: Functions <script language="JavaScript">

Without a function:



WestLake Internet Training

Introduction to JavaScript for New Programmers Page 25



value="Eenie" onClick="alert('Ouch, that value="Meenie" onClick="alert('Ouch, that value="Miney" onClick="alert('Ouch, that


With a



function:

type="button" type="button" type="button"

value="Eenie" onClick="ouchalert();">

value="Meenie" onClick="ouchalert();" >

value="Miney" onClick="ouchalert();" >



All of the buttons have the same functionality, as they all result in the same alert:

However, whereas the first set of buttons' actions are coded inline with each HTML tag, the second set all call upon the same function that then executes the alert:

The advantage to using functions is two-fold: as mentioned, the code's redundancy is lessened. In addition, the chances of making a syntax error within the executed JavaScript statements is reduced, as the same statement does not need to be retyped every time it is invoked.

Writing a JavaScript Function Writing a function entails:

• declaring and naming the function. • writing the statements that are executed by the function.

The <script> Tag All JavaScript code not embedded within an existing html tag (including functions) should fall between a set of <script> tags. This tag does support attributes, including the language attribute responsible for defining the language (and, if desired, version of that language): <script language="JavaScript">

WestLake Internet Training

Introduction to JavaScript for New Programmers Page 26

JavaScript functions are often stored in the of an html document inside a set of script tags, although they may actually be stored anywhere needed within the HTML document. As functions often need to be available as soon as the document loads, it is standard to store them in the head of the page. In addition to seeing <script> tags store functions, you may also come across script tags that simply store JavaScript statements. These tags may be placed in the html code as needed— whether it be in the head, in the body, or between the close of the body and the html tags. Each of these statements would execute as it was read by the browser.

Hiding Scripts from Older Browsers Older browsers that do not support JavaScript will read the code nested in <script> tags as content. Unfortunately, this results in the display of the code as text on a page. This error can be avoided by enclosing the JavaScript code in an html comment, as follows: <script language="JavaScript"> This ensures browsers that do not support the language will ignore the code, and browsers that do support JavaScript can still execute the code. The two slashes (//) prior to the closing html comment are single-line JavaScript comment symbols. These are needed to tell JavaScript to ignore the closing piece of the html comment (- - >), as the - - code is actually used to decrement a variable and will be intepreted as such without the single-line comments.

NOTE

Multiple Line Comments You may also comment multiple lines of code by enclosing them between /* and */. It is a good idea to get into the habit of commenting code with authoring notes that clarify the code's intended purpose.

Declaring, Naming, and Writing a Function Functions in JavaScript are declared and named using the following syntax: function function_name() { statements to execute when function is called; } where function is a reserved term responsible for declaring a function, and function_name is the name given to the function being declared. Although a function is named as the coder desires, all syntax rules (such as using underscores instead of spaces and not using reserved terms) apply. Notice that a set of parentheses immediately follows the function name. These parentheses are required and are used to enclose additional information, just as a method’s set of parentheses encloses any required parameters. This will be discussed in more detail later. For now, be sure to know that the parentheses are required syntax for both declaring the function as well as calling the function. The statements to be executed by the function are nested within the { and } characters. Although spaces are ignored, writing functions in a standard format will quicken the debugging process. Standard notation is shown above.

WestLake Internet Training

Introduction to JavaScript for New Programmers Page 27

Invoking a Function Once a function has been declared and named, any object in the page can call (invoke) the function. To invoke a function, simply call it by its name via the desired event handler. For example, the following button invokes the ouchalert() function when it is clicked:

Passing an Argument to a Function Functions are very helpful for making code more concise. However, with just the information you have now, functions are not very flexible they do exactly the same thing every time they are run. JavaScript is capable of customizing a function based on the information sent by a particular function call. In other words, the function can execute differently based on data passed to the function when it is invoked. For example, a single function named flipcolor() might change the background color of the page based upon the button that was clicked. If the red button was clicked, the background would change to red; if the blue button was clicked, the background would change to blue. Using the same function to achieve these changes requires passing data to the function by the function call. In other words, it is necessary to pass an argument to the function. For example, consider the following code (flipcolor.html), which displays four buttons that change the background color of the page accordingly:

The code for the page follows: Setting bgColor via a Function <script language="JavaScript"> WestLake Internet Training

Introduction to JavaScript for New Programmers Page 28

Notice that the code is essentially the same as in the previous exercise, with the exception of the code in bold. The code in bold adds two components:

• An argument is passed to the function when it is called. The buttons’onClick event handlers call the function flipcolor() and pass that function an argument (a string of text such as 'red', 'green', 'blue', or 'white').
type="button" type="button" type="button" type="button"

value="Red" onClick="flipcolor( 'red')"> value="Green" onClick="flipcolor( 'green')"> value="Blue" onClick="flipcolor( 'blue')"> value="White" onClick="flipcolor( 'white')">

• The function then passes that argument to the statements it executes. The function receives the argument passed to it (in this case, a string of either 'red', 'green', 'blue', or 'white') and assigns that argument to a local variable that can be used throughout the function. In this example the variable mynewcolor stores the sent argument and passes that argument throughout the function as needed: function flipcolor(mynewcolor) { document.bgColor = mynewcolor; }

So, when the red button is clicked, 'red' is assigned the value of mynewcolor. When the 'green' button is clicked, green is assigned to the value of mynewcolor, and so forth. The new value of mynewcolor is then used throughout the function to change the background of the page. Passing arguments to a function makes the the function much more flexible.

WestLake Internet Training

Introduction to JavaScript for New Programmers Page 29

Concatenating Strings and Variables Suppose that instead of having the function flipcolor() change the background color, you want the function to alert the user with the message, “You just pressed the button_color_here button!” (e.g., “You just pressed the red button!”) To do this, flipcolor() would be written as follows: function flipcolor(mynewcolor) { alert("You just pressed the " + mynewcolor + " button!"); } Notice that any text enclosed in pairs of quotes displays literally; the local variable that you want interpreted is not. In addition, the text and the local variable are joined by the + operator, which concatenates the strings and the variables into one seamless message. Anytime you want the value of a variable displayed in conjunction with a string of text, it is necessary to join the pieces of the string with the variable using the concatenation (+) operator.

WestLake Internet Training

Introduction to JavaScript for New Programmers Page 30

Exercise 3: Modifying Your Color Picker to use Functions In this exercise, you will modify the color picker so that it uses functions, rather than redundant code. To complete this exercise:

1. Open exercise3-temp.html in Notepad. You will be modifying the color picker to use functions. The code is currently as follows and matches that of the code in the completed version of the last exercise, with commented instructions for completing this exercise: Color Picker TAGS, AND SAFEGAURD OLDER BROWSERS FROM DISPLAYING THE CODE AS TEXT. */ //-->



2. Edit the script to declare a function named flipandalert(). Don’t forget to place the function in <script>… tags and html comment tags. Also, be sure to place the function in the of the document. 3. Create a local variable in the parentheses of the function. Name this variable color_value. 4. The function, flipandalert(), should execute two statements when called upon:

WestLake Internet Training

Introduction to JavaScript for New Programmers Page 31

• The first statement changes the background color of the page to the color passed to it by the function call. • The second action alerts the user to the page's change in background color. 5. Modify the buttons so that each onClick event handler calls the flipandalert() function and sends the appropriate argument to that function. 6. Save the page and test it in a browser. If it is not working correctly, go back and fix the code as needed.

If you are done early... • Modify the function so that the alert() statement runs first. Save the page and test a button in the browser. What do you notice? Did the change apply to every button’s behavior? • Modify the alert statement so that it displays “Red is a great background color”.

WestLake Internet Training

Introduction to JavaScript for New Programmers Page 32

A Possible Solution to Exercise 3 As contained in exercise3-done.html: Color Picker <script language="JavaScript">



WestLake Internet Training

Introduction to JavaScript for New Programmers Page 33

Introduction to Scalar Variables JavaScript has three types of variables: scalar variables, which store a single value; array variables, which store a list of values; and objects, which store data bundled with methods and properties for working with that data. This section will explore scalar variables. The last section used a scalar variable. Remember, the argument passed to a function had to be stored in a local variable. That variable (called color_value) was scalar, as it contained a single value. Scalar variables are useful for temporarily storing a single value that can be used later within a script. In addition, the value of the variable can be modified. For now, consider a simple prompt dialog that asks for the user’s name. To do anything with the entered information (such as alert a customized message to the user), the entered information must be stored in a variable. The code to prompt a user for her first name and store that entry into a variable called first_name is as follows: var first_name = prompt('What is your first name?', ''); The above statement does the following:

• initiates a variable called first_name through the use of the reserved term var. Variables in JavaScript should be declared the first time they are used by using the reserved word var. • prompts the user for information. • stores the entered information in the variable named first_name. Names of variables (also known as identifiers) can use numbers, letters, and underscores. The first character of the name, however, cannot be a number. Each of the above bullets will be discussed in detail.

JavaScript Data Scalar variables can hold one of four types of data: a string, number, Boolean value (i.e., true or false), or null. The four types of data which a scalar variable can hold are described below:

WestLake Internet Training

Introduction to JavaScript for New Programmers Page 34

Data Type String Number Boolean Null

Description

Possible Value "Mickey Mouse" 25 true null

A literal string of text or characters Any number, not in quotes A logical true or false The absence of any value

The following illustrates assigning different types of data to a scalar variable: var age; age=25; var firstname; firstname = "Mickey"; var mouse; mouse = true; firstname = null; Notice that the assignment (=) operator does not mean equal to in JavaScript. Instead, it is responsible for setting the value of a variable. The first statement assigns the number 25 to the variable age. Notice that the number 25 is not surrounded by quotes, therefore it is interpreted as a numerical value rather than a string. The second statement assigns the string "Mickey" to the variable firstname. As the second statement illustrates, anytime a string is assigned to a variable, it must be placed in quotation marks. The third statement assigns the Boolean value true to the variable mouse. Again, true is not treated as a string because it is not nested in quotation marks. The fourth and final statement assigns null to firstname. null is a special value that deallocates the variable (which previously held the value "Mickey") and frees the memory it occupied for later use. Once variables are assigned a value, they can be used in other JavaScript statements in the page. For example, once the first three statements above are executed, an alert() method could display a customized message dependent on the values of those variables: alert("Hello, " + firstname + ", you are " + age + " years old."); Notice that quotes do not surround the variable names so that they are not treated as strings.

Avoiding Redundant Var Declarations There are a number of ways to reduce the redundancy in declaring variables. For example, the following code: var age; var firstname; var mouse; age = 25; firstname = "Mickey"; mouse = true; code could be condensed to: var age, firstname, mouse; age = 25; firstname = "Mickey"; mouse = true; The first statement declares all three variables at once, and the latter statements assign values to each variable. Alternatively, the above code could be condensed by assigning the value in the declaration: var age=25

WestLake Internet Training

Introduction to JavaScript for New Programmers Page 35

var firstname = "Mickey"; var mouse = true; In the above case, each line initiates the variable, as well as assigns a value to that variable.

Storing Information from a Prompt As discussed, the window.prompt() method displays a dialog requesting a single field of text input from the user. For example: prompt("Please enter your first name:", "fir stname"); yields the dialog:

To do anything with the entered information, however, the information must be stored in a variable. For example: var first_name; first_name = prompt("Please enter your first name:", ""); This statement prompts the user for his first name. When OK is pressed, the user’s entry is assigned to the first_name variable. If the user clicks the Cancel button instead, the value null is assigned to the variable. The above code can be condensed further into a statement that initiates the variable, prompts the user, and assigns her entry to the initiated variable all within one line: var first_name = prompt("Please enter your first name:", "");

A More Complete Example Open the file howdyalert.html in your browser. The following dialog displays as you open the page:

After entering the information and clicking OK, the page displays as follows:

WestLake Internet Training

Introduction to JavaScript for New Programmers Page 36

Finally, clicking the button results in an alert message that welcomes the user by name:

In short, the user is prompted to enter her name upon loading the page. Her entered information is stored in a variable and later used to display a custom alert message when the howdyalert() function is called. The JavaScript code responsible for this follows: Assigning Prompt Data to a Variable <script language="JavaScript">
This code brings up a very important fact about the placement of the <script> tags, and how that placement controls when the JavaScript is executed. All code between the <script> and tags, except for code within functions, is executed immediately as it is loaded in the browser. Since the <script> block is within the head, the statement:

WestLake Internet Training

Introduction to JavaScript for New Programmers Page 37

var firstname = prompt("Enter your first name:", ""); is the very first statement that is executed, even before the body of the page is loaded. Once the user enters her name, that name is assigned to the firstname variable and the browser displays the rest of the page.

WestLake Internet Training

Introduction to JavaScript for New Programmers Page 38

Exercise 4: Making Your Color Picker More Personal In this exercise, you will modify your color picker to display the user’s name. This entails prompting the user for her first name, storing that information in a scalar variable, and then using that scalar variable in an alert message as follows:

To complete this exercise:

1. Open exercise4-temp.html in Notepad. The code for this exercise is the same as the code in the completed version of the last exercise: Color Picker <script language="JavaScript">



2. Create a variable called firstname that uses a prompt() method to request the user’s information as soon as the page is requested. This variable should be placed in the <script>

WestLake Internet Training

Introduction to JavaScript for New Programmers Page 39

tags prior to the flipandalert() function, as this will ensure the statement is executed before the page loads. 3. Modify the alert() dialog message to address the user by name. 4. Save the page and test it in a browser. If the page does not work, go back into the code and make changes as necessary.

If you are done early... • Add a second prompt that appears as the page loads asking for the user’s last name. Then, modify the alert statement so it makes use of both the user’s first name and last name.

WestLake Internet Training

Introduction to JavaScript for New Programmers Page 40

A Possible Solution to Exercise 4 As contained in exercise4-done.html: Color Picker <script language="JavaScript">



WestLake Internet Training

Introduction to JavaScript for New Programmers Page 41

Here are the top 5 reasons to choose WestLake’s classroom-based, handson method of instruction: #5: Web Development Skills are the #1 need of employers today We have the skills you need to compete in the 21st century! We guide you all the way from Beginning HTML to the cutting edge technologies like XML, ASP, and Wireless Markup Language. We do it all. #4: Our courseware makes learning and retaining the material enjoyable and easy Written by our seasoned training staff, our courseware contains the complete instructional content of the class, making it easy to review later what you have learned. And because WestLake is vendor-neutral, you will always get a balanced perspective on each technology. #3: Service you receive – before, during, and after class Before class, our expert registration staff will help you select the class that’s right for you. During class, you will be served food and drink, and be encouraged to ask questions. After class, support is available from trainers seven days per week via our online forums. #2: Small Class Sizes We limit our class size to 12 students. Every student works on a state of the art PC with high speed Internet access. In addition, there is a monitor next to your desk where you can see what is on the instructor’s screen – no more straining to see the difference between a colon and a semi-colon at 50 paces. And the #1 reason students select WestLake as the Web Development Training Leader: Students leave prepared to immediately apply what they have learned. Rather than sitting through a boring lecture, you will spend a large portion of class time doing hands-on development with the technology you are learning. Leave prepared to immediately tackle your projects! If you have any questions regarding our classes, please email [email protected] or call us tollfree at 866.WESTLAKE (866.937.8525) and select option 1. You can register at the same number or online at http://www.westlake.com/register/. To have WestLake bring a class to you, please email [email protected] or call us tollfree at 866.WESTLAKE (866.937.8525) and select option 2.

WestLake Internet Training

Introduction to JavaScript for New Programmers Page 42

Related Documents