About

Tuesday, 14 June 2011

JavaScript

The Name "JavaScript"

In this manual, we refer to the language we are learning as JavaScript, which is what it is usually called. However, the name JavaScript is owned by Netscape. Microsoft calls its version of the language JScript. The generic name of the language is EcmaScript.

The HTML DOM

The HTML Document Object Model (DOM) is the browser's view of an HTML page as an object hierarchy, starting with the browser window itself and moving deeper into the page, including all of the elements on the page and their attributes. Below is a simplified version of the HTML DOM. 
As shown, the top-level object is window. The document object is a child of window and all the objects (i.e, elements) that appear on the page (e.g, forms, links, images, tables, etc.) are descendants of the document object. These objects can have children of their own. For example, form objects generally have several child objects, including textboxes, radio buttons, and select menus.

JavaScript Syntax

Basic Rules

  1. JavaScript statements end with semi-colons.
  2. JavaScript is case sensitive.
  3. JavaScript has two forms of comments:
    • Single-line comments begin with a double slash (//).
    • Multi-line comments begin with "/*" and end with "*/".
Syntax
// This is a single-line comment

/*
 This is
 a multi-line
 comment.
*/

Dot Notation

In JavaScript, objects can be referenced using dot notation, starting with the highest-level object (i.e, window). Objects can be referred to by name or id or by their position on the page. For example, if there is a form on the page named "loginform", using dot notation you could refer to the form as follows:
Syntax
window.document.loginform
Assuming that loginform is the first form on the page, you could also refer to this way:
Syntax
window.document.forms[0]
A document can have multiple form elements as children. The number in the square brackets ([]) indicates the specific form in question. In programming speak, every document object contains an array of forms. The length of the array could be zero (meaning there are no forms on the page) or greater. In JavaScript, arrays are zero-based, meaning that the first form on the page is referenced with the number zero (0) as shown in the syntax example above.

Square Bracket Notation

Objects can also be referenced using square bracket notation as shown below.
Syntax
window['document']['loginform']

// and 

window['document']['forms[0]']
Dot notation and square bracket notation are completely interchangeable. Dot notation is much more common; however, as we will see later in the course, there are times when it is more convenient to use square bracket notation.

Where Is JavaScript Code Written?

JavaScript code can be written inline (e.g, within HTML tags called event handlers), in script blocks, and in external JavaScript files. The page below shows examples of all three.

Code Sample: JavaScriptBasics/Demos/JavaScript.html

<html>
<head>
 <title>JavaScript Page</title>
 <script type="text/javascript">
  window.alert("The page is loading");
 </script>
</head>
<body>
<p align="center">
 <span onclick="document.bgColor = 'red';">Red</span> |
 <span onclick="document.bgColor = 'white';">White</span>
</p>
<script type="text/javascript" src="Script.js"></script>
</body>
</html>

Code Sample: JavaScriptBasics/Demos/Script.js

document.write("Hello, there!");
Code Explanation
As this page loads, an alert will pop up that says "The page is loading" as shown below. 
After the user clicks the OK button, the page will finish loading and will appear as follows. 

The text "Hello, there!" is written dynamically by the code in JavaScriptBasics/Demos/Script.js. We will look at the code in this file .

JavaScript Objects, Methods and Properties

JavaScript is used to manipulate or get information about objects in the HTML DOM. Objects in an HTML page have methods (actions, such as opening a new window or submitting a form) and properties (attributes or qualities, such as color and size).

Code Sample: JavaScriptBasics/Demos/JavaScript2.html

<html>
<head>
 <title>JavaScript Page</title>
 <script type="text/javascript">
  //Pop up an alert
  window.alert("The page is loading");
 </script>
</head>
<body>
<p align="center">
 <span onclick="document.bgColor = 'red';">Red</span> |
 <span onclick="document.bgColor = 'white';">White</span> |
 <span onclick="document.bgColor = 'green';">Green</span> |
 <span onclick="document.bgColor = 'blue';">Blue</span>
</p>
<script type="text/javascript" src="Script2.js"></script>
</body>
</html>

Code Sample: JavaScriptBasics/Demos/Script2.js

/*
This script simply outputs
 "Hello, there!"
to the browser.
*/
document.write("Hello, there!");

Methods

Methods are the verbs of JavaScript. They cause things to happen.

window.alert()

HTML pages are read and processed from top to bottom. The JavaScript code in the initial script block at the top of JavaScriptBasics/Demos/JavaScript2.html calls the alert() method of the window object. When the browser reads that line of code, it will pop up an alert box and will not continue processing the page until the user presses the OK button. Once the user presses the button, the alert box disappears and the rest of the page loads.

document.write()

The write() method of the document object is used to write out code to the page as it loads. In JavaScriptBasics/Demos/Script2.js, it simply writes out "Hello, there!"; however, it is more often used to write out dynamic data, such as the date and time on the user's machine.

Arguments

Methods can take zero or more arguments separated by commas.
Syntax
object.method(argument1, argument2);
The alert() and write() methods shown in the example above each take only one argument: the message to show.

Properties

Properties are the adjectives of JavaScript. They describe qualities of objects and, in some cases are writable (can be changed dynamically).

document.bgColor

The bgColor property of the document object is read-write. Looking back at JavaScriptBasics/Demos/JavaScript2.html, the four span elements use the onclick event handler to catch click events. When the user clicks on a span, JavaScript is used to change the value of the bgColor property to a new color.

The Implicit window Object

The window object is always the implicit top-level object and therefore does not have to be included in references to objects. For example, window.document.write() can be shortened to document.write(). Likewise, window.alert() can be shortened to just alert().

The getElementById() Method

A very common way to reference HTML elements is by their ID using the getElementById() method of the document object as shown in the example below.

Event Handlers

In JavaScriptBasics/Demos/JavaScript2.html, we used the onclick event handler to call JavaScript code that changed the background color of the page. Event handlers are attributes that force an element to "listen" for a specific event to occur. Event handlers all begin with the letters "on". The table below lists the HTML event handlers with descriptions.

HTML Event Handlers
Event HandlerElements SupportedDescription
onblur a, area, button, input, label, select, textarea the element lost the focus
onchange input, select, textarea the element value was changed
onclick All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a pointer button was clicked
ondblclick All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a pointer button was double clicked
onfocus a, area, button, input, label, select, textarea the element received the focus
onkeydown All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a key was pressed down
onkeypress All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a key was pressed and released
onkeyup All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a key was released
onload frameset all the frames have been loaded
onload body the document has been loaded
onmousedown All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a pointer button was pressed down
onmousemove All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a pointer was moved within
onmouseout All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a pointer was moved away
onmouseover All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a pointer was moved onto
onmouseup All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a pointer button was released
onreset form the form was reset
onselect input, textarea some text was selected
onsubmit form the form was submitted
onunload frameset all the frames have been removed
onunload body the document has been removed

Exercise: Using Event Handlers

Duration: 15 to 25 minutes.
In this exercise, you will use some of the event handlers from the table above to allow the user to change the background color of the page.
  1. Open JavaScriptBasics/Exercises/JavaScript.html for editing.
  1. Modify the page so that...
    • when it is finished loading an alert pops up reading "The page has loaded!"
    • when the "Red" button is clicked, the background color turns red and an alert pops up reading "The background color is now Red."
    • when the "Green" button is double-clicked, the background color turns green and an alert pops up reading "The background color is now Green."
    • when the "Orange" button is clicked down, the background color turns orange and an alert pops up reading "The background color is now Orange."
    • when the mouse button is released over the "Blue" button, the background color turns blue and an alert pops up reading "The background color is now Blue."

Code Sample: JavaScriptBasics/Exercises/JavaScript.html

<html>
<head>
 <title>JavaScript Page</title>
 <script type="text/javascript">
  window.alert("The page is loading.");
 </script>
</head>
<body>
<form>
 Click the button to turn the page
 <input type="button" value="Red"/>
 <br/><br/>
 Double click the button to turn the page
 <input type="button" value="Green"/>
 <br/><br/>
 Click down on the button to turn the page
 <input type="button" value="Orange"/>
 <br/><br/>
 Release the mouse while on the button to turn the page
 <input type="button" value="Blue"/>
</form>
<hr/>
<script type="text/javascript" src="Script.js"></script>
</body>
</html>

0 comments:

Post a Comment