CIS 207 | Web Page Development - HTML |
JavaScript is a powerful, object-based scripting language; JavaScript programs can be embedded directly in HTML web pages. When combined with the Document Object Model (DOM) defined by a web browser, JavaScript allows you to create Dynamic HTML content and interactive client-side web applications. JavaScript syntax is based on the popular programming languages C, C++, and Java, which makes it familiar and easy to learn for experienced programmers. At the same time, JavaScript is an interpreted scripting language, providing a flexible, forgiving programming environment in which new programmers can learn.
Let's check out some JavaScript special effects.
We can use innerHTML to change a loaded page (HERE).
Or, we could get ideas from others like the TinyBox code provided by Michael Leigeber. This script provides a neat effect for a modal window that can accept any AJAX or HTML input. For example, a Picture, or a Web page, a PopUp Ad, or your favorite YouTube video.
In this chapter, we will take a a look at how to create Web pages whose content and layout can be modified using built-in programs. In our discussion of Forms, we learned about accessing programs involving forms and CGI scripts and running programs that are stored and run off the Web server. Here are some disadvantages to this approach:
These issues led to the development of programs, or scripts, that could be run from the Web browser on the user's own computer (the client) as illustrated below.
Client-side programs solve many problems associate with CGI scripts. Computing is distributed over the Web so that no one server is overloaded with handling programming requests. Since the user does not have to wait for data to be sent over the Internet to the Web server, client-side programs are likely to be more responsive to the user. Client-side programs can never completely replace CGI scripts because needed data is stored on the server.
In the early 1990s, before the WWW became hugely popular, the programmers at Sun Microsystems foresaw a day when even common consumer devices, such as refrigerators, toasters, and garage door openers, would all be networked and capable of being controlled by a single operating system. They developed such an operating system and based it on a language called Oak. Oak was designed to be extremely reliable and flexible. Although the project failed, Oak worked so well that Sun realized it could be used on the Internet. Oak was modified in 1995 and renamed Java. Sun Microsystems (Java) released a product called HotJava, which could run programs written in the Java language. HotJava acted as a Java interpreter, which means it could interpret a Java program and run it for the user. Because Java interpreters could be created for different operating systems, users could run Java in any environment, including Unix, Windows, DOS, and Macintosh operating systems. Just as Web pages are designed to be platform-independent, so was Java.
Netscape quickly incorporated a Java interpreter into Netscape Navigator 2.0, making HotJava unnecessary. Microsoft followed suit with Internet Explorer 3.0.
With Java, the user downloads a program, called an applet, along with the Web page. The browser, with the built-in Java interpreter, is able to run the applet from the user's own machine, freeing up the Web server for other purposes.
One problem with Java was that nonprogrammers found it difficult to learn and use. Also, the JDK (Java Developer's Kit) is needed to create and compile programs. To simplify the process, a team of developers from Netscape and Sun created JavaScript. JavaScript is a subset of Java with several differences. Users don't need to work with a developer's kit or to compile a JavaScript program, and JavaScript commands can be inserted directly into an HTML file rather than being placed in a separate applet. JavaScript is not as powerful a computing language as Java, but it is simpler to use, and it meets the need of many users wanting to create programmable web pages.
Internet Explorer uses a variation of JavaScript called JScript. For all practical purposes, JScript is identical to JavaScript, but some JavaScript commands are not supported in JScript, and vice versa. You can find scripting information on Microsoft's web site pertaining to JScript and VBScript at http://www.microsoft.com/scripting.
Like HTML and CSS, the development of a JavaScript standard has been turned over to an international body, called the European Computer Manufacturers Association. The standard developed by the ECMA is called ECMAScript, though browsers still use the common name, JavaScript. Most major browsers support the ECMA-262 standard.
The JavaScript language was invented by Brendan Eich at Netscape. The development of this Standard started in November 1996. The first edition of this ECMA Standard was adopted by the ECMA General Assembly of June 1997. That ECMA Standard was submitted to ISO/IEC JTC 1 for adoption under the fast-track procedure, and approved as international standard ISO/IEC 16262, in April 1998.
Check out the JavaScript vs. Java link.
Check out these links to JavaScipt programming information. Many of these sites offer free scripts that you can copy and paste into your own web page.
There are two ways to create a JavaScript program:
Or, you can run it in this JavaScript Scratch Pad.
Placing the code in an external file allows you reuse code in other pages. For example, I use an external JavaScript to define the pencil image map at the top of my pages. If the pencil ever changes, I only have to change this one external file, and the changes appear in all my pages that use the pencil.
Let's stop and take a look at the external file pencil.js which is used in this page, and other pages with the pencil. Point your browser to http://www.halharris.com, and view the source code. Each page that uses the pencil will have the following code to tell the browser to load the JavaScript file named pencil.js:
<script language="JavaScript1.3" src="pencil.js">
</script>
Now, let's append the JavaScript file named pencil.js to the URL in the address bar and press ENTER to load the pencil.js file. Click VIEW, SOURCE to see the JavaScript code in the external file.
Note that the external file has no HTML code in it at all. It only contains the JavaScript commands.
Placing JavaScript commands in an external file makes it more difficult for users to see your code, but, as you can see, it is not too difficult to load the external file and view the source code. In this tutorial, we will enter the code directly into the HTML file.
The <SCRIPT> tag is a two-sided tag that identifies the beginning and end of a client-side program. The <SCRIPT> tag is used to distinguish JavaScript code from HTML text. The general syntax for this tag is:
<SCRIPT SRC=URL LANGUAGE="language">
Script commands and comments
</SCRIPT>
where URL is the URL
or filename of an external document containing the
program code, and language
is the language that the program is written in. The SRC property is required only if you place your program in a separate file. The
LANGUAGE property is needed so the browser knows which interpreter to use with
the client-side program code. Since the default LANGUAGE value is "JavaScript"
it can be omitted.
Your program can be placed anywhere within the HTML file. We'll later look at functions which are typically placed in the <HEAD> tag to insure that they are executed before subsequent calls to that function down in the <BODY> tag.
Older browser that do not support JavaScript will display the JavaScript commands as text. We can hide JavaScript commands from older browsers by combining HTML comment tags with JavaScript comment tags. Recall that HTML ignores any tags it does not recognize. Likewise, JavaScript ignores any HTML tags it encounters.
As you may recall, we create HTML comments with the <!> tag. JavaScript supports similar comment tags, using a set of double slashes ( // ) at the beginning of a line to tell the browser to ignore the line and not interpret it as a JavaScript command.
The syntax for hiding JavaScript commands from browsers that do not support them follows:
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide script from browsers that don't support JavaScript
JavaScript commands
// Stop hiding -->
</SCRIPT>
How It Works: When a browser that doesn't support scripts encounters this code, it first ignores the <SCRIPT> tag, as it does any tag it does not recognize. The next line it sees is the start of the HTML comment tag, which doesn't close until the > symbol in the second to last line. On the other hand, a browser that supports JavaScript recognizes the <SCRIPT> tag and will ignore any HTML tags found between the <SCRIPT> and </SCRIPT> tags.
JavaScript provides two methods to display text on a web page: the document.write( ) and document.writeln( ) method. The syntax for these commands is:
document.write("text_and_html_codes");
document.writeln("text_and_html_codes");
(which
adds a carriage return)where text_and_html_codes
is a string of characters and/or HTML codes that
you want to appear on the web page. For example, the following method will
display the heading "Welcome" in the web page:
document.write("<h1>Welcome</h1>");
The document.write( ) and document.writeln( ) methods reflect the object-oriented nature of the JavaScript language. In this case, document is an object, and write or writeln are actions that can be applied to the object document. The word method means an action applied to something existing on your web page.
Text can be enclosed within double or single quotation marks which allows the use of the quote or double quote in the text sent to the browser. For example, we could use:
document.write('Come meet David "Bud" Davis');
to have the following string sent to the browser:
Come meet David "Bud" Davis
JavaScript Syntax Issues: Most JavaScript commands and names
are case-sensitive. Browsers will not recognize Document.Write( )
since it will expect lower case letters. Also, each JavaScript command line
ends with a semicolon to distinguish it from the next command line in the
program.
Pop Quiz #1 on page 8.11
So far, we've learned how to insert text into a web page using the document.write( ) method. Since we had to specify the text explicitly, the program did no more than what we could have accomplished by placing the text directly in the HTML file.
A variable is a named element in a program, used to store and retrieve information. Variables are useful because they can store information created in one part of your program and use that information in another part. For example, you could create a variable named "Year" to store the value of the current year, and use the Year variable at different locations in your program.
To assign the value 2002 to the variable "Year," you would enter the following JavaScript command:
Year=2002;
With the year variable assigned a value, you can use the document.write( ) method to display this value on the web page as follows:
document.write(Year);
This would cause the text "2002" to appear on the web page. You can combine text with the variable value by using a plus symbol (+), as in the following example:
document.write("This year is " + Year);
This command will display the text This year is 2002 on the web page.
Variable Name Rules:
CAREFUL: If you have problems with your JavaScript code, double-check that you are following these four rules. If you still have a problem, check to make sure you have not used a JavaScript keyword for a variable name.
Variable names are case-sensitive. A variable named Year is different from a variable named year or YEAR.
JavaScript supports four different types of variables:
Before you can use a variable in your program, you have to create it. This is known as declaring a variable. You declare a variable in JavaScript by using the var command or by assigning the variable a value. For example, any of the following commands will create a variable named "Month":
var Month;
var Month = "December";
Month = "December";
The first command creates the variable without assigning it a value, while the second and third commands both create the variable and assign it a value. It is considered good programming style to use the var command, but not required. It is best to place a variable declarations at the beginning of your program and place comments to describe its purpose.
Although JavaScript does not provide a date data type, it does allow you to create a date object, which is an object that contains the date information. The date object can be saved as a variable in your JavaScript program. There are two ways to save a data as a variable:
variable = new Date("month, day, year, hours:minutes:seconds");
(text string to specify date)
or
variable = new Date(year, month, day, hours, minutes, seconds);
(value to specify date)
where variable
is the name of the variable that will
contain the date information, and month, day, year, hours, minutes and
seconds
indicate the date and time. The keyword new
in
the above example indicates that you're creating a new object. For example, each
of the following commands will create a variable named "SomeDay" corresponding
to the date of June 15, 2002 at 2:35pm:
SomeDay = new Date("June, 15, 2002, 14:35:00");
or
SomeDay = new Date(2002, 5, 15, 14, 35, 0);
Note that you must subtract 1 from the month number (5 instead of 6 for June) since JavaScript numbers the months starting with zero. Also, hours are expressed in military time.
If you omit the date and time information, JavaScript returns the current system date and time. For example, the following command creates the variable "Today" that contains information about the current date and time:
Today = new Date();
JavaScript actually stores the date and time information as a numeric value - the number of milliseconds since January 1, 1970. This allows us to add and subtract dates to calculate time between dates and times. We can use some of the built-in JavaScript date methods to translate these numbers into into dates.
We can use the getDate( ) method to obtain the day of the month from a date or date variable. For example:
DayValue = DateObject.getDate();
will place the day of the month of the DateObject
into the
variable DayValue
. For example to retrieve the day of the month
from the Today
variable, you would use the command:
ThisDay = Today.getDate();
The getMonth( ) method will extract the value of the current month. Because JavaScript starts counting the months with zero for January, will will add one to the month number with the following syntax:
ThisMonth = Today.getMonth()+1;
If the current date is June 28th, the value of the ThisMonth
variable will be six.
The getFullYear( ) method extracts the year value from the date variable. To store the value of the current year in a variable named ThisYear, we can use the following syntax:
ThisYear = Today.getFullYear();
If the date was October 15, 2002, the value stored in the variable
ThisYear
will be 2002.
The getYear( ) method was made obsolete by the Y2K issue, since it would return 1902 for the year in the above example.
Expressions are JavaScript commands that assign values to your variables. Expressions always use some sort of assignment operator, such as the = sign, but they also can contain a variety of other operators, which are elements that perform actions within the expressions. The + operator performs the action of :
getMonth( )+1
; document.write("Today is
" + Today);
We will use the following command to print the number of days left until Christmas:
document.write("Only " + DaysLeft + " days until
Christmas");
Arithmetic operators perform simple mathematical calculations. Here is a list of some of the arithmetic operators with examples of how they work:
Operator | Description | Example |
+ | Adds two values together (binary operator) | var Men=20;
|
- | Subtracts one value from another (binary operator) | var Price=1000;
|
* | Multiplies two values together (binary operator) | var Width=50;
|
/ | Divides one value by another (binary operator) | var People=50;
|
% | Shows the remainder after dividing one value by another (binary operator) | var TotalEggs=64;
|
++ | Increases a value by one (Increment is a unary operator) | var Eggs=12;
|
-- | Decreases a value by one (Decrement is a unary operator) | var Eggs=12;
|
- | Changes the sign of a value (Negation is a unary operator) | var MyGain=50;
|
Binary operators work on two elements in an expression. Unary operators work on only one variable. The increment operator can be used to increase the value of a variable by one. In the following example, the value of the variable x is 100 and the value of the variable y is 101.
x = 100;
y = x++;
The decrement operator has the opposite effect, reducing the value of a variable by one. The following example assigns the value 100 to the x variable and 99 to the y variable:
x = 100;
y = x--;
The negation operator changes the sign of a variable as indicated in the following example:
x = -100;
y = -x;
In this example, the value of the x variable is -100, and the value of y is opposite that, or 100.
Expressions assign values using assignment operators. We've already used the assignment operator, the equals (=) sign. JavaScript provides other assignment operators that manipulate elements in an expression and assign values within a single operation. One of these is the += operator. The following two expressions create the same result:
x = x + y;
x += y;
In both expressions, the value of the x variable is added to the value of the y variable and stored in x. We can also use assignment operators with numbers to increase a variable by a specific amount. For exmple, to increase the value of the x variable by 2, we can use either of the following two expressions:
x = x + 2;
x += 2;
Here are other JavaScript assignment operators:
Operator | Description | Example |
= | Assigns the value of the variable on the right to the variable on the left | x = y
|
+= | Adds the two variables and assigns the result to the variable on the left | x += y
|
-= | Subtracts the variable on the right from the variable on the left and assigns the result to the variable on the left | x -= y
|
*= | Multiplies the two variables together and assigns the result to the variable on the left | x *= y
|
/= | Divides the variable on the left by the variable on the right and assigns the result to the variable on the left | x /= y same as x = x / y
|
%= | Divides the variable on the left by the variable on the right and assigns the remainder to the variable on the left | x %= y
|
Another way of performing calculations is to use one of the JavaScript built-in Math methods. These methods are applied to an object called the Match object. The syntax for applying a Math method is:
value = Math.method(variable);
where method
is the method you apply to a variable, and
value is the resulting value. For example, to calculate the absolute value of a
variable named NumVar, you use the "Abs" method as follows:
AbsValue = Math.abs(NumVar);
and the value of the AbsValue variable is set to the absolute value of the NumVar variable. Here are other math methods supported by JavaScript.
Keep in mind that case is important with JavaScript commands. For instance, you MUST type "Math" with the upper case "M" and the "ath" must be in lower case letters in order to avoid JavaScript errors.
A function is a series of commands that either performs an action or calculates a value. A function consists of the function name, which defines it; parameters, which are values used by the function; and a set of commands that are run when the function is used. Not all functions require parameters. The general syntax of a JavaScript function is:
function function_name(parameters){
JavaScript commands
}
where function_name
is the name of the function,
parameters
are the values sent to the function, and
JavaScript commands
are the actual commands and expressions executed
when the function is called. The curly braces { } are used to mark the beginning
and end of the commands in a function. The group of commands set off by the
curly braces is called a command block.
Function names, like variable names, are case-sensitive. XMASDAYS and XmasDays are considered different function names. The function name must begin with a letter or underscore ( _ ) character and cannot contain spaces. The parameters must be placed within parentheses followed by the function name, and each parameter must be separated from the others with a comma.
To call a function, use the following command:
function_name(values);
where function_name
is the name of the function you want
to run, and values
are the values substituted for each of
the function parameters.
Consider the following function which displays a message with the current date:
function ShowDate(date) {
document.write("Today is " + date + "<br>");
}
The function name is ShowDate. It has one parameter, date. There is just one line in the function's command block, which displays the current date along with the text string "Today is ". To run a function, you insert a JavaScript command containing the function name and any parameters it requires. This process is known as calling a function. To call the ShowDate function, you enter the following commands:
var Today = "3/14/2002";
ShowDate(Today);
The first command creates a variable named Today
and assigns it
the string, "3/14/2002"
. We called the function with the second
command, and passed the value of the variable Today
as the
parameter that this function requires. The result of calling the ShowDate
function is that the following appear on the web page:
Today is 3/14/2002
We can use a function to calculate a value. This process is known as returning a value, and is achieved by placing a return command along with a variable or value, at the end of the function's command block. Consider the following Area function:
function Area(Width, Length) {
var Size = Width*Length;
return Size;
}
The Area function calculates the area of a rectangle, given its width and length, and places the value in a variable named "Size". The value of the Size variable is returned by the function. A simple JavaScript program that uses this function might appear as follows:
var x = 8;
var y = 6;
var z = Area(x,y);
The first two commands assign the values 8 and 6 to the x and y variables. The values of both of these variables are sent to the Area function, corresponding to the width and length parameters. The Area function uses these values to calculate the area, which it then returns, assigning that value to the z variable. In this example, 48 is assigned to the value of the z variable.
Function definitions must be placed before the command that calls the function. Often, just to make sure that function definitions are placed before the commands that call them, programmers will place all function definitions within the <HEAD> and </HEAD> tags to insure that they precede the code in the body which calls the function.
You will create an XmasDays function in the tutorial to calculate the number of days until Christmas.
Let's take a look at the BMI Index Form that we glanced at previously in the forms chapter.
A conditional statement is one that runs only under certain conditions. The most often used conditional statement is the If statement.
An If statement has the following syntax:
if(condition) {
JavaScript commands
}
where condition
is an expression that is either true or
false. If the condition is true, then the JavaScript commands
in the command block are executed. If not, then no action is taken.
A comparison operator compares the value of one element with another, creating a Boolean expression that is either true or false. Here are two examples of Boolean expressions:
x < 100;
y == 20;
In the first example, if x is less than 100, this expression returns the value true. If x is 100 or greater, the expression is false. In the second example, the y variable must have an exact value of 20 for the expression to be true. Note that this comparison operator uses a double equal sign ( = = ) rather than a single one. The single equal sign is an assignment operator and is not used for making comparisons in JavaScript. Here is a list of the comparison operators in JavaScript:
Operator | Description | Example |
= = | Returns true if variables are equal | x =
y |
!= | Returns true if variables are not equal | x != y |
> | Returns true if the variable on the left is greater than the variable on the right | x > y |
< | Returns true if the variable on the left is less than the variable on the right |
x < y |
> = | Returns true if the variable on the left is greater than or equal to the variable on the right | x >= y |
< = | Returns true if the variable on the left is less than or equal to the variable on the right | x <= y |
A logical operator connects two or more Boolean expressions. One such operator is the && operator, which returns a value of true only if all the Boolean expressions are true. For example, the following expression will be true only if x is less than 100 and y is equal to 20:
(x < 100) && (y == 20);
Here is a list of some of the logical operators used by JavaScript:
Operator | Description | Example |
&& | AND (two ampersand symbols) Returns true only when both expressions are true. | var x=20;
|
|| | OR (two pipe symbols - Shift + backslash) Returns true only when either expression is true | (x==20) && (y==25) returns true
|
| | NOT (one pipe symbol - Shift + backslash) Returns true if the expression is false, and false if the expression is true. | |(x==20) returns false
|
Sometimes we want an IF statement to run one set of commands if a condition is true and a different set of commands if the condition is false. The syntax for an If...Else statement follows:
if(condition) {
JavaScript commands if condition is true
} else {
JavaScript commands if condition is false
}
where condition
is an expression that is either true or
false. Here is an example:
if(Day=="Friday") {
document.write("The weekend is almost
here!");
} else {
document.write("Hi There!");
}
In this example, if Day equals the string "Friday" the text "The weekend is almost here!" is printed. However, if Day does NOT equal "Friday" the text "Hi There!" appears.
We can nest IF statements by placing an IF statement inside another IF statement.
An array is an ordered collection of values referenced by a single variable name. The syntax for creating an array variable is:
var variable = new Array(size);
where variable is the name of the array variable, and size is the number of elements, or distinct values, in the array. Specifying a size for an array is optional. If you don't specify a size, JavaScript will automatically increase the size of the array as you add more elements. The code for creating an array named "Month" would be:
var Month = new Array();
Once the array is created, you create values for each individual element in the array. To create values for the Month array, you can use the following commands:
Month[1] = "January";
Month[2] = "February";
Month[3] = "March";
Month[4] = "April";
Month[5] = "May";
Month[6] = "June";
Month[7] = "July";
Month[8] = "August";
Month[9] = "September";
Month[10] = "October";
Month[11] = "November";
Month[12] = "December";
Be able to recognize the above code as being part of an array.
These commands create 12 new elements in the Month array. Each element is identified by its index, which is an integer that appears between the brackets. For example, the element "March" has an index value of 3 in the Month array.
The first element in an array has an index value of 0, the second item has an index value of 1, etc. There are actually 13 elements in the Month array. The first element, Month[0] has a null value. We started with 1 because we want the index numbers to match the month number - makes it a lot easier to keep track in our code.
We can use variables in place of index values. For example, if the variable "MonthNumber" has the value 5, then:
Month[MonthNumber]
would be equal to the value of Month[5] which is "May". We call this statement "Month sub MonthNumber".
Loops allow commands to be run more than once. Oftentimes, a program will need to run the same group of commands over and over - for example, if you wrote a program to print invoices, you would need to run the same group of commands that actually print the invoice over and over, once for each invoice you printed. A program loop is a set of instructions that is executed repeatedly. There are two types of loops:
The FOR LOOP allows you to create a group of commands that will be executed a set number of times through the use of a counter. You set an initial value for the counter, and each time the command block is executed, the counter changes in value. When the counter reaches a value above or below a certain stopping point, the loop ends. The general syntax of the FOR LOOP is:
for(start; condition; update) {
JavaScript commands
}
where start
is the starting value of the counter,
condition
is a Boolean expression that must be true for the loop to
continue, and update
specifies how the counter changes in
value each time the command block is executed. Here is an example of a FOR LOOP
that counts to ten on the screen:
for(Nbr=1; Nbr<11; Nbr++) {
document.write("The counter variable Nbr is
equal to " + Nbr + "<br>");
}
The counter in this example is the variable Nbr
, which starts
with an initial value of 1. As long as the value of Nbr
is less
than 11, the condition for running the loop is met. When the value of Nbr
reaches 11, the loop stops. The expression "Nbr++
" indicates that
each time the command block is run, the value of Nbr
increases by
1.
Check out the example.
The FOR LOOP is not limited to incrementing the value of the counter by 1. You can specify one of several different counting methods. Here are some examples:
for(i=10; i>0; i--)
example
for(i=0; i<=150; i+=15) example
for(i=2; i<64; i*=2)
example
Take a close look at each of these FOR LOOP possibilities. What will each one do? Click example to see it in action.
The WHILE LOOP runs a command group as long as a specific condition is true, but it does not use counters. The general syntax of the WHILE LOOP is:
while(condition) {
JavaScript commands
}
where condition is a Boolean expression that can be either true or false. As long as the condition is true, the group of statements will be executed by JavaScript. Here is an example of a WHILE LOOP that counts to ten on the screen:
var Nbr=1;
while(Nbr<11) {
document.write("The value of Nbr is " + Nbr);
Nbr++;
}
Check out the example.
Another Loop example.