Web Development Tutorials




  
  

The Javascript Language

Creating a dynamic Web page involves writing scripts to change property settings and to call up processing methods associated with Browser Objects surrounding the page. These scripts are written in the JavaScript language and appear on the page to which dynamic effects are applied.

Client-Side Scripting

JavaScript is a relatively easy-to-learn, simple-to-use language. It provides much of the processing capability of full-featured programming languages, but without the investment of time and effort needed to acquire a full range of programming skills. Certainly, JavaScript does not provide the range of capabilities of standard programming languages. Nevertheless, it does offer the common arithmetic, logical, and control capabilities that the Web developer is most likely to need to make Web pages interactive and dynamic.

JavaScript is a client-side scripting language, meaning the ability to run JavaScript code is built into modern browsers. Code is embedded on the Web page along with HTML and CSS formatting codes. Thus, scripts have direct processing access to the layout, style, and content components of the page. The browser interprets and runs scripts locally without having to make return trips to the server to update page content or otherwise respond to user actions and requests.

As a client-side language, JavaScript has inherent limitations when it comes to information processing activities. It cannot access the local hard drive nor can it make data access requests to the Web server. Therefore, the language cannot be used to access files or databases, the crucial prerequisites for e-commerce or other major server-based applications. It can assist the server by manipulating data downloaded to the browser, but it cannot process data directly on the server. Despite these limitations, however, JavaScript can perform invaluable browser-side services to make Web pages interactive with users and responsive to their needs.

History of JavaScript

Despite the similarity in names, JavaScript is not the Java language nor even a subset of Java. The two languages are unrelated except for minor syntactical similarities. JavaScript was developed by Brendan Eich at Netscape to allow Web developers to build interactive Web pages that run on the browser or client-side. JavaScript does this by manipulating the DOM to update content on a page. While in development, JavaScript was known by its codename "Mocha". Orginally, it was to be called LiveScript. However, as part of a licensing deal with Sun Microsystems, Netscape agreed to include the Java environment in its Netscape browser in exchange for permission to rename LiveScript to JavaScript.

After the release of JavaScript, Microsoft developed its own client-side scripting language known as JScript. JScript is mostly compatible with JavaScript, despite small differences. Netscape later submitted JavaScript to the European Computer Manufacturers Association (ECMA) for standardization. The result was a language officially known as ECMAScript. Because of the historical use of the name JavaScript, it it is likely that the name will continue to be used to refer to JavaScript, JScript, and ECMAScript. The most current version of JavaScript is 1.8. However, version 1.5 is the release most compatible with current versions of JScript and ECMAScript. Therefore, this tutorial will focus on JavaScript 1.5.

Placement of JavaScripts

The most common convention is to code JavaScript in a separate, external .js file. The <script> tag is then included in the <head> section of the page to call the page. This location and general format for a script section is shown in Figure 1-21.

<!DOCTYPE HTML>
<html>
<head>
    <title>Web page</title>
    <script src="javascript.js"></script>
</head>
<body>
    Page text and HTML...
</body>
</html>

Figure 1.2. JS files can be placed in the <head> or just before the closing </body> tag.

The external javascript file is shown below.

window.onload = init;

function init() {
    additonal javascript code...
}

Figure 1.3. When the window.onload event occurs, the init function is executed.

JavaScript Functions

The first statement in the javascript file is window.onload. This statement or event listener is triggered when the browser window loads and calls the init() function. The most reliable way to know that it's safe to reference DOM objects is to confirm that the browser has loaded the entire page. If references to DOM elements are made prior to the page load, errors will occur. The init() function contains javascript statements, references to DOM elements, or calls to other functions. A JavaScript function works just like functions in other languages. That is, it is assigned a name by which it can be called upon to perform its processing, and it contains one or more statements to perform whatever processing it is designed to do. The general structure of a JavaScript function is shown in Figure 1-22.

function functionName() {
    statement1;
    statement2;
}

Figure 1-22. Structure of a JavaScript function.

A function is identified by the keyword function, followed by a programmer-supplied name for the function, and followed by a set of parentheses that optionally enclose data values needed by the function to carry out its processing. Processing statements are coded between { and } characters which identify the beginning and end of the function. The statements themselves normally are coded one per line ending with a semicolon (;). A semicolon is optional unless two or more statements appear on the same line, in which case a separating semicolon is required. One or more named functions can appear inside the <script> section depending on how many different processing routines are required by the page.

Case Sensitive Syntax

It is important to remember that JavaScript code is case sensitive; you cannot indiscriminately use upper- and lower-case notation. With few exceptions, JavaScript is written in lower-case characters. You have some flexibility in coding programmer-supplied names; otherwise the syntax of the language is strict. Pay close attention to the formats presented here for JavaScript statements.

Using Functions to Change Styles

As mentioned, scripts make reference to HTML elements through their id values, and they access element properties and methods through their names. Therefore, it is common to write functions using these references. The following function, for example, assigns a different text size, color, and boldness to the HTML tag identified by the attribute id="MyTag".

window.onload = init;

function init()
{
  changeStyle();
}

function changeStyle()
{
  document.getElementById("myTag").style.fontSize = "2em";
  document.getElementById("myTag").style.fontWeight = "bold";
  document.getElementById("myTag").style.color = "red";
}

Figure 1.23. Javascript code that changes style settings

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Web Page</title>
    <script src="javascript.js"></script>
</head>
<body>
    <p id="myTag">This is a paragraph that has its styling changed.</p>
</body>
</html>

Figure 1.24. HTML code that implements the JS code in Figure 1.23.

The paragraph must be assigned an id so it can be identified to the script. The script references the tag through this id in setting the text and color style properties of the paragraph. Similar scripting techniques are used to activate methods associated with tags.

Calling Functions with Event Handlers

Functions appearing in a JavaScript file are not automatically run when the page loads. They must be explicitly called upon, by name, to perform their processing. The most common way to call a function into action is on the basis of some user event surrounding the page, for example, the user clicks the mouse on an HTML tag. Within the init() function the event handler is associated with a function call.

A popular event handler for trapping user events is the onclick handler. This handler detects a mouse click on an HTML element and can trigger a function call in response. The general format for associating an event handler with a function call is shown below.

window.onload = init;

function init()
{
  var myvar = document.getElementById("elementID");
  myvar.onclick = changeStyle;
}

Figure 1.25. Using an event handler to call a function.

When the page loads, the init() function is called. The init() function contains the event listener, in this case, the event is the clicking of the HTML element with the assigned id value MyTag. When the onlick event occurs, the function ChangeStyle() is called.

window.onload = init;

function init()
{
  var myvar = document.getElementById("myTag");
  myvar.onclick = changeStyle;
}

function changeStyle()
{
  document.getElementById("myTag").style.fontSize = "2em";
  document.getElementById("myTag").style.fontWeight = "bold";
  document.getElementById("myTag").style.color = "red";
}

Figure 1.26. Javascript code that changes style settings when tag is clicked.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Web Page</title>
    <script src="javascript.js"></script>
</head>
<body>
    <p id="myTag">This is a paragraph that has its styling changed.</p>
</body>
</html>

Figure 1.27. HTML code that implements the JS code in Figure 1.23.

This event handler and associated script are illustrated below. The exact code shown above appears on this page to change the styling of the following paragraph when it is clicked.

This is a paragraph that has its styling changed.

Figure 1.28. Click the paragraph to see the change from Figure 1.26 and 1.27.

As in the case of DOM properties and methods, there are numerous page events and associated event handlers that need to be learned. The following table lists several event handlers that can be applied to trap mouse events. Other handlers are introduced throughout these tutorials.

Event Handler Event
onclick The mouse button is clicked and released with the cursor positioned over a page element.
ondblclick The mouse button is double-clicked with the cursor positioned over a page element.
onmousedown The mouse button is pressed down with the cursor positioned over a page element.
onmousemove The mouse cursor is moved across the screen.
onmouseout The mouse cursor is moved off a page element.
onmouseover The mouse cursor is moved on top of a page element.
onmouseup The mouse button is released with the cursor positioned over a page element.

Figure 1.29. Event handlers associated with mouse events.

Inline Scripts

In the early years of JavaScript, it was common to apply javascript commands directly within the HTML. The general format for this code arrangement is shown below:

<p id="myTag"
    onclick="document.getElementById('myTag').style.fontSize='2em';
    document.getElementById('myTag').style.fontWeight='bold';
    document.getElementById('myTag').style.color='red'">
    This is a paragraph that has its color changed.</p>

Figure 1.30. Deprecated (OLD) way of inlining JavaScript.

While it is common to still find HTML pages with embedded JavaScript, this is no longer considered a best practice.

Functions Calling Functions

It is often the case that script processing required for a page is not, or cannot, be contained in a single function called by an event handler. A common situation is that a first function is called by an event handler to initiate processing, and that additional functions are called to carry out additional processing. There is a cascade of calls from one function to another as separate functions carry out their specialized processing tasks.

One function calls upon the processing of a second function simply by specifying its name. This format for one function to call a second function is shown in Figure 1-31.


function functionName1() {
    functionName2();
    continued processing...
}

Figure 1.31 A JavaScript function calling another function.

A call is made from one function to a second function by supplying its name. Processing control passes to the second function where, upon completion of processing, control returns to the original function. The original function continues its processing at the statement following the function call.

Consider the following script outline containing three functions, process1(), process2(), and process3(). The first function is called from an event handler coded in a button. This function calls a second function which calls a third function to carry out page processing.

function process1() {
    ...
    process2()
    ...
}

function process2() {
    ...
    process3()
    ...
}

function process3() {
    ...
}

Figure 1.32. Chaining together JavaScript calls.

During execution of process1(), a call is made to function process2(). Script control passes immediately to process2(), which begins executing its statements. One of the statements is a call to function process3(). Again, control passes immediately to process3(), which begins executing its statements. After process3() finishes its processing, control returns to process2() where processing continues with the statement following the function call. After process2() finishes its processing, control returns to process1() at the statement following the original call to process2(). After process1() finishes its processing, the script ends.

Although in most cases involving dynamic styling you will be able to restrict processing to a single function called from a single event handler, there are situations where a cascade of function calls is needed. Often this need arises when designing functions that are functionally tight. That is, rather than including all possible processing tasks inside a single function, multiple functions with distinct and focused tasks are created. In these cases, more that one function may be needed, and they may need to call each other, to complete processing.


TOP | NEXT: JavaScript Comments