JavaScript Basics

Terminology  |  Event Handlers  |  Using JavaScripts  |  Examples  |  Useful Links

The purpose of this page is to convey a basic understanding of JavaScript. A second page follows with more detailed discussion and more examples of scripting. Follow the links at the bottom of this page if you seek more detailed information.

JavaScript is a programming language designed for Web pages that describes data and procedures in terms of objects, methods, and properties, rather than variables, routines, and statements. Unlike HTML, JavaScript is case sensitive. JavaScript is plain text and when created in a text editor needs to be saved as a text (ASCII) file. Newer editions of full featured WYSIWYG HTML editors support some JavaScripting, and often enable coding in their page source windows. If you begin doing JavaScript by cutting and pasting you may often need to modify a few parts of the scripts, such as names of objects. Many JavaScripts are available on the WWW, and links to some popular JavaScript sites are provided below.

JavaScript can enhance the dynamics and interactive features of Web pages by enabling calculations, checking forms, writing interactive games, adding special effects, customizing graphics selections, data binding, and more. JavaScript is an interpreted language that runs in the user's browser. JavaScript code works on any computer platform with a JavaScript capable browser, such as Navigator 2.0 or later, or Microsoft Internet Explorer 3.0 or later. JavaScript capable browsers may allow disabling JavaScript in their preferences. JavaScript is easier to use than are programming languages. With JavaScript, developers do not need to compile a program or work with a developer's kit. Also, the many JavaScripts available on the Internet can easily be modified and adapted to your own pages.

A team of Netscape and Sun Microsystems developers originally created JavaScript. In 1998 the European Computer Manfacturers Association (ECMA) announced the adoption of a standard Internet scripting language based on JavaScript 1.1 that resolved the incompatibilities that existed in scripting between various browser implementations. Microsoft, Netscape, and other browser companies agreed to follow the specification. The standard is called ECMAScript, though the common name, JavaScript, has persisted. The most recent version of JavaScript is 1.3 (ECMA-262). Version 1.3 requires Netscape 4.06 or newer and Microsoft Internet Explorer (IE) 4.0 or newer. IE actually uses JScript, a modified version of JavaScript that does not support all JavaScript commands. I therefore recommend testing your pages, and using a Netscape browser when viewing Web pages with JavaScripting.

JavaScript Terminology. JavaScript programming uses specialized terminology.

  • Dot Syntax is used to combine terms, for example the object and property window.status;, or the object and method document.write("Hello World");.
  • Objects refers to windows, documents, images,  tables, forms, buttons or links, etc. Because you can have more than one of an object type, objects should be named. Objects have properties that act as modifiers. The things that objects can do are called methods. Objects can be thought of as things and methods as actions.
  • Properties are object attributes. Background color as a document property is expressed by document.bgcolor. Object's properties are defined by using dot syntax: the object's name, a period, and the property name.
  • Methods are actions applied to particular objects, that is, things that they can do. For example, document.open(index.htm) or document.write("text here"), where open() and write() are methods and document is an object.
  • Events associate an object with an action. JavaScript uses commands called event handlers to program events. Event handlers place the string "on" before the event. For example, the onMouseover event handler allows the page user to change an image, and the onSubmit event handler can send a form. Page user actions typically trigger events. For example onClick="javascript:formHandler()" calls a JavaScript function when the user clicks a button or other element.
  • Functions are statements that performs tasks. JavaScript has built-in functions and you can write your own. A function is a series of commands that will perform a task or calculate a value. Every function must be named. Functions can specify parameters, the values and commands that run when the function is used. A written function can serve to repeat the same task by calling up the function rather that rewriting the code for each instance of use. A pair of curly brackets {} surrounds all statements in a function.
  • Values are bits of information. Values types are Number, String, Boolean, Null, Object, and Function. A string value is a string of characters enclosed in quotes. A Boolean is either true or false. An Object value type is any value associated with an object.
  • Variables contain values. The var keyword is used to declare variables. Variables use the equal sign to specify their value, such as name="form1". Assignments place a value in a variable and are accomplished using the equal sign. Variables can be numeric, string, Boolean or null. Variables are created by declaration using the var command, such as var date;. Variables can also be created using an initial value state, such as var month = January;, or simply month = January;. Variable names are restricted. They must begin with a letter or an underscore, only letters, numbers or underscores can be used, they cannot contain spaces, and they cannot use JavaScript reserved words. And, of course, they are case sensitive.
  • Expressions are commands that assign values to variables. They always use an assignment operator, such as the equals sign. The variable declaration var month = January; is an expression. Statements and commands end with a semicolon.
  • Operators are used to handle variables. Arithmetic functions are operators.
  • Comparisons evaluate the value of one variable in relation to another variable or a value specified in an expression.

JavaScript Event Handlers. Actions by page users trigger event handler commands in the JavaScript. The program will then perform whatever commands are assigned to the event. Common event handlers are listed in the following table.

Event Handler


onAbort The user stopped loading a page
onBlur The user moves from an object
onChange The user changed an object
onClick The user mouse-clicked an object
onError An error occurred in the script
onFocus The user activates an object
onLoad The object has been loaded
onMouseover The cursor has moved over the object
onMouseout The cursor has moved off the object
onSelect The user selected the object
onSubmit The user submitted a form
onUnload The user leaves the window

Using JavaScript.

JavaScript scripts can be embedded in an HTML page or can reside in a separate page.  JavaScript is often placed in the <head> section of the HTML document, but can also be placed in the <body>.  JavaScript object attributes can also be placed in HTML element tags. You can use JavaScript in an HTML document in the following ways:

  • As statements and functions within <script> and </script> tags.
  • By specifying a file as the JavaScript source using the <src> attribute of the <script> element.
  • By specifying a JavaScript expression as the value of an HTML attribute and as event handlers within certain other HTML tags.

The first method places the JavaScript between the <script> and </script> tags. When specifying a script only the tags <script> and </script> are essential. It is recommendable to specify the script language as an attribute of the script element. Browsers currently assume JavaScript, but other programming languages could become popular in the future. The standard to open scripting is <script language="JavaScript">. The script language attribute can also specify the version of JavaScript. It is also recommendable to specify the MIME type of the script, to denote to the browser that the script is plain text. This is accomplished with the attribute type="text/javascript".

The following example script redirects the browser to a page, named javascript.html. The object is window, the variable property is location, and the value equals the specified HTML file.

<script language="javascript1.2" type="text/javascript">
<!-- Begin hiding script
// End hiding script-->

Comment tags, <!-- comment here -->, should bracket any script. The <!-- and // --> tags hide comments in HTML and prevent scripts from displaying in browsers that do not interpret it or do not have JavaScript enabled. The double slashes are the signal characters for a JavaScript single-line comment. The longer, multi-line comment signal characters are /*, which tells JavaScript to ignore everything until the end comment operator, */, is encountered in the code. Adding comments to code is often used to provide a reminder of what you are doing and to facilitate understanding of the code by other users.

The second method uses a separate file to contain the script. This is useful if many pages in a Web site use the same scripts, thus eliminating the need to place the same code in every page. Some authors use this method to hide their scripts from other authors, but you can always find the scripts in your browser cache after you access the page. External JavaScript files must be of the type "text/plain" and must be saved with a .js extension. Web browsers retrieve the script file as they would a CSS page or an image file. If no additional scripting is placed between the <script> and </script> tags no comment tags are needed. Add the source attribute to the <script> tag, as follows.

<Script src="myjavascript.js" language="JavaScript1.2" type="text/javascript"></script>

The third method places JavaScript in HTML tags. Event handlers like onMouseOver are a perfect example of an easy to add, rollover effect script. Move your mouse pointer over the adjacent image and that event will invert the color by displaying a second image file. This is accomplished with JavaScript code enclosed in the hyperlink anchor element tag as seen in the following sample of code. Note that the object is named "logo" and the JavaScript event handlers specify the image file names.

<a href="back.html" onMouseover="document.logo.src='images/js2.gif'"
<img src="images/js.gif" name="logo" border=0 height=50 width=80></a>

The following script, also added to the anchor tag, places a message in the status bar when the mouse moves over the link. Use this Test link to test the example. The page this link takes you to employs the redirect script above to return you to this page. Here is the JavaScript that places the message in the status bar.

<a href="redirect.html" onMouseover="self.status='Your mouse pointer is on a hyperlink for the page "redirect.html".';return true">Test</a>

The next example, added to the body tag, displays an alert window when the page containing the tag opens. The alert contains the message between apostrophes within the parenthesis, which you can customize.  Try it.  Testing, 1, 2, ...

<body text="#000000" bgcolor="#FCE072" onLoad="alert('WELCOME. This page is just for testing the JavaScript  SORRY.')">

JavaScript Examples. In the following examples I do not include the <script>and </script> tags, HTML tags or comment lines. These examples are employed using the methods described above. The first example is a method for displaying text in a Web page. The syntax for this method can also be writeIn, a method that attaches a break to each line of text. The writeIn method should be used with preformatted text.

document.write("This is where you place the text that will appear in the Web page.")

The write method also permits use of HTML tags within the parenthesis, as seen below.

document.write("<b>Hello World.</b>")

These two examples explicitly specified the text to be written. You can also include variables you have created. The first two lines below are the portion of the script that creates the variables used in the third line. The plus operator performs the function of combining the elements.

var month = April;
var date = fifteenth;

document.write("Remember, your taxes are due on " + month + date);

Functions. JavaScript operators and expressions can be combined to create functions. For a function to work properly it must be placed in the HTML file before the command that calls it. A function consists of the word "function" followed by a name, parenthesis and an open brace on the first line, then the function statements on the following line and the closing brace. The parenthesis contain all parameters separated by commas. The curly braces (brackets) designate the command block. Event handlers are usually used to call functions. Note how the function formHandler in the GO TO form script below is handled by the form button event onClick. JavaScript function names are case-sensitive. Function names begin with a letter or an underscore and cannot have a whitespace. The JavaScript function syntax follows.

function function_name(value, value){
   JavaScript commands and expressions

Conditional Statements. A conditional statement is a command that runs only under specified conditions. Conditions require operators. Comparison operators compare two elements and return a Boolean expression, either true or false. Logical operators connect two or more Boolean expressions. Here follows the general syntax of a conditional statement that runs if a condition is met.

if (condition){
    JavaScript commands and expressions

This example uses the conditional statement with an else command separating two command blocks, the first of which runs if the condition is met, the other if not.

if (month=="December"){ alert("Happy Holidays."); } else {

This conditional statement is a command to break a framed document out of the frame to display in its own window.

if (top.frames.length > 0) {

Forms and JavaScripts. Handling a form is a common JavaScript task. A JavaScripted form relies on one or more event handlers, such as onClick or onSubmit, that trigger a JavaScript action when the user performs a command, like clicking a submit button. Form control objects can include the usual graphical interface elements, like a text entry field, buttons, radio buttons, pop-up menus or check boxes.

The next example is a simple GO TO drop-down menu of hyperlinks.  Place the first section of code in the <head> section.

<script language="JavaScript"> <!-- Hiding
function formHandler(form){
var URL = document.form.site.options[document.form.site.selectedIndex].value;
window.location.href = URL;
// --> </script>

Place this script portion in the <body> section where the form is located. The name of this form must match the name used in the script above in the formHandler function. You can customize the links and their labels, and the number of links.

<form name="form">
<select name="site" size=1>
<option value="authoring.html">Building a Web page</option>
<option value="elements.html">Elements of Web Design </option>
<option value="frames/creating_frames.html">Creating Frames </option>
<option value="ftp.html">File Transfer Protocol</option>
<option value="javascript.html">JavaScript </option>
<option value="multimedia.html">Multimedia </option>
<input type=button value="Go!"

For your cutting and pasting convenience, the product of the scripted form is presented in a separate file.

The last example creates a text snake that follows your mouse pointer around the page. Go to the page to see it in action and use the page source to view the script.

This page is continued on the JavaScript Programming page.

Parts of this page are condensed in a JavaScript Basics PowerPoint and in a Word file.

Useful JavaScript Links.