JavaScript Basics

In this lesson of the JavaScript tutorial, you will learn...
  1. To work with the HTML DOM.
  2. To follow JavaScript syntax rules.
  3. To write JavaScript inline.
  4. To write JavaScript in script blocks.
  5. To create and link to external JavaScript files.
  6. To work with JavaScript objects, methods, and properties.
  7. To reference HTML elements with JavaScript.
  8. To use event handlers.

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 and in JavaScriptBasics/Demos/JavaScript.html again shortly.

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).

To illustrate objects, methods and properties, we will look at the code in JavaScriptBasics/Demos/JavaScript2.html, a slightly modified version of JavaScriptBasics/Demos/JavaScript.html, which we looked at earlier, and at the code in JavaScriptBasics/Demos/Script2.js.

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 Handler Elements Supported Description
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

JavaScript Basics Conclusion

In this lesson of the JavaScript tutorial, you have learned the basics of JavaScript. Now you're ready for more.

To continue to learn JavaScript go to the top of this page and click on the next lesson in this JavaScript Tutorial's Table of Contents.

Use of this website implies agreement to the following:

Copyright Information

All pages and graphics on this Web site are the property of Webucator, Inc. unless otherwise specified.

None of the content on this website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of web pages

This content may not be printed or saved. It is for online use only.


Linking to this website

You may link to any of the pages on this website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

This website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).

For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm.