JavaScript Programming

This page follows the JavaScript Basics page.

Using Dates in JavaScripts. JavaScript allows for the creation of date objects that can be saved as variables in either of two ways, as seen in the code below. The first is in the order month, day, year, hours:minutes:seconds, and the second is year, month, day, hours, minutes, seconds. In JavaScript the months are numbered from 0 to 11 and hours are exressed from 0 to 23. Dates defined without hours, minutes and seconds will use a default of zero for each. The following codes each creates a new variable for midnight, January 1st, 2000.

var Millenium=new date("January, 1, 2000, 00:00:00");
var Century=new date(2000, 0, 1, 0, 0, 0);
JavaScript stores time information as the number of milliseconds since January 1, 1970, and calculates the time from this base using built-in functions. In the following sample function the JavaScript commands use the date object and extract the day, month, and year numerical variables, then combine them in a text string with slash separators. The .getFullYear method returns the entire year, and the .getYear method returns the last two numerals of the year, except for the year 2000, when it returns 2000. When comparing years always use the .getFullYear method.
function TodaysDate (){
var Today=new Date(); var ThisDay=Today.getDate();
var ThisMonth=Today.getMonth()+1;
var ThisYear=Today.getFullYear();
return ThisMonth+"/"+ThisDay+"/"+ThisYear;

Other retrievable values are in the form of getSeconds(), getMinutes(), getHours(), getDay(), and getTime(), for seconds, minutes, hours, day of the week, and milliseconds since Jan. 1, 1970 respectively.

Arrays are collections of objects. An ordered collection of values referenced by a single variable name is an array. Arrays are created using the variable command. Each object in an array is numbered according to its sequential psition in the array. A typical example is the creation of a text array for the names of the months. JavaScript only supports numeric determination of date varialbles. An array can be used to convert numeric values to text variables. In the following function, named MonthText, the array is used to return the name of the month. The only parameter of the function is MonthNumber. For example, MonthText(5) will return May. Here is the code for the function with the array.

function MonthText (MonthNumber) {
   var Month = new Array();
return Month{MonthNumber}; }
Using Operators. Operators that perform mathematical calculations are called arithmetic operators. Those that work on two variables are called binary operators. For example, the + operator can add two numbers or combine two elements. Operators that work with one variable are called unary operators. These include increment, decrement and negation operators. Assignment operators manipulate elements in an expression and assign values. For example, the equals sign assigns a value to a variable.

In the following function the arithmetic multiplier is used to find volume of a rectangular solid.

function FindVolume(Height, Width, Depth); {
   var Volume = Height*Width*Depth;
return Volume;

The following JavaScript uses the negation operator to define a variable.

var Credit = 100;
var Debit = -Credit

Using Math Methods. JavaScript also has built-in Math methods for performing certain calculations. These all follow the syntax of Math.method, where the method is the specific calculation. The following example rounds the variable Number to the closest integer and stores it in the variable Rounded.

var Rounded = Math.round(Number);

Other Math methods include Math.abs for absolute value, Math.sin and other trigonometric functions which return a number in radians, Math.floor and Math.ceil for rounding down or up to the nearest integer, Math.exp raises the value of E to the value of the number, Math.log returns the natural logarithm of the number, Math.random returns a random number between 0 and 1, and Math.toString converts the number to a text string. All these Math methods act on a single variable. Several others act as comparatives of, or act on two numbers. Math.max(x,y) and Math.min(x,y) return the greator or lessor, resp[ectively, of two number variables. Math.pow(x,y) returns the value of the first number raised toth pwer of the second number.

Program Loops. Code that is repeated is called a loop. Loops can repeat a specified number of times, or until a condition is met. The For loop creates a group of commands that will execute a specific number of times, as controlled by a counter. The While loop runs as long as a condition is met, and does not employ a counter. The condition is expressed by Boolean operators.

Working with Objects. JavaScript reserves object names to refer to particular objects. For example, object reserved names include form, window, frame, anchor, link, location, and document. An object can also be designated using assigned names, a necessity when several objects, such as forms, are found in the same page using scripts that refers to them. Objects have a hierarchy which may need to be followed when specifying them, such as window.document.form.button. Objects have associated properties, which vary depending on the object. Specific keywords are used to identify properties, such as name, target, status, method, action, and others.

The properties of some objects can be controlled using JavaScripts. Here are several examples that might occur in the same document.

document.title="Tutorial One.";
document.status="Complete each step.";
Objects can also have associated methods. Methods are actions that objects can prform or that can be applied to objects. Here are some distinct examples that are not likely to occur together.
document.write="Hello World."

Browser software contains built-in scripting, including objects. The World Wide Web Consortium has set standards for this hierarchical collection of objects, known as the Document Objects Model (DOM). This object collection is also referred to as the Browser Object Model. Not all browsers have the same built-in objects.

Event Handlers. In the previous page a table of events and their corresponding actions is provided. An event is a specific action that causes the browser to run a command. JavaScript supports a variety of events. An event handler is code added to an HTML tag that runs when an event occurs in relation to the tag element. Event handlers are associated with specific objects, such as onSubmit and onReset being associated with forms, and onClick being associatable with a variety of objects. In the following example a page background color is modified using a set of radio buttons and the onClick event handler.

Background Color: Gray     Tan     White

<form>Background Color:
<input type="radio" name="bgcolor" onClick.bgcolor="ffffff""> Gray
<input type="radio" name="bgcolor" onClick.bgcolor="cccccc""> Tan
<input type="radio" name="bgcolor" onClick.bgcolor="ffcc99""> White </form>

Emulating Events consists of using javaScript to performan action for a user, such as placing the cursor in a password field on loading a page. In the following sample of code the cursor is moved to the password field of the login form. The method focus makes the input box active. The function is defined in a script and the emulation is placed in the body tag

function StartForm() {

<body onLoad="StartForm">

Form Validation is a common use of event handlers. If a user enters an incorrect value in an input the browser can display a dialog box with a custonizable message informing the user of the error and providing any necessary directions.

A word about Web design and development tools. While understanding code is important, you can save a lot of time by using state-of-the-art Web development software, like Dreamweaver MX. Such tools create many of the common JavaScripts.

Check out the JavaScript Basics PowerPoint to review these pages.
Recommended Readings:
The Web Wizard’s Guide to JavaScript by Steven Estrella
JavaScript for the World Wide Web by Tom Negrino and Dori Smith
Useful JavaScript Links are available in the previous, JavaScript Basics page.