JavaScript Tutorial
JavaScript is an object-oriented language designed to be embedded in Web pages.
The user's browser must know how to interpret JavaScript commands, a common ability of browsers nowadays. JavaScript uses a Document Object Model (DOM) that
considers each HTML element as an object that can respond to events such as the
clicking of the mouse. Each object has also properties that can be queried or
altered. While sharing a piece of its name with the Java language, both
languages must not be confused.
An important difference between JavaScript and Java is that the strong typing of
Java does not exist in JavaScript. JavaScript does not demand that the
variables' type be declared, nor is it necessary to declare the type of
parameters and the return values of functions. There are also differences
regarding the classing of objects and the inheritance between classes.
JavaScript supports a small set of data types representing numeric, Boolean and
string values. The similarity between the two languages is stronger in all that
concerns to expression syntax and basic control-flow constructs.
A piece of JavaScript embedded in an HTML page is called a script. A script can
be written within the Web page, but it can also be a file on its own. JavaScript
expressions can be included as attribute values in an HTML tag. To create a
block of JavaScript within an HTML page, you must use the SCRIPT tag, including
the name of the language in the start tag.
<SCRIPT LANGUAGE="JavaScript">
<!--
...
...here goes your coding...
...
//-->
</SCRIPT>
The reason of the inner comment tags (<!-- -->) is to avoid that older
browsers that do not allow scripting detect the script as an error in HTML
coding. The double slash (//) is JavaScript's notation for a one-line comment.
In these days, all the browsers accept scripting, so this hiding may be safely
omitted. In case you want to be more specific about the version of JavaScript
that you are using, the version number can be included in the LANGUAGE attribute:
"JavaScript1.2". The most used version of JavaScript is 1.5, which became available in Netscape 6, Internet Explorer 5.5, and Firefox 1. This version adheres to the standard ECMA-262 Edition 3. The latest version released is JavaScript 2.
If you prefer to write your script in a separate file, this file must not
include HTML statements, it must have a name ended with ".js", and it must be
referenced in the SCRIPT tag.
<SCRIPT language="JavaScript" src="script.js"></SCRIPT>
This technique has the advantage that you may centralize all your functions and
thus avoid unnecessary duplication. Besides making your pages smaller, if the
need for a change arises, it may be done at only one place. If you do not use an
external script file, you should put the code with your JavaScript code between
the HEAD tags, thus ensuring that it is read before any other element. However,
a script framed as it was explained before can be included at any place of the page being outside a tag.
JavaScript’s syntax
The syntax of JavaScript statements is similar to the one of other high-level languages like C, Pascal, or Java. Variable and function names are sensitive to the case used, so “myvar” is not the same that “myVar”. JavaScript keywords can be written using upper o lower case. A semicolon at the end of the statement is optional if the statement ends the line. Otherwise, the syntax is a free one.
Object hierarchy
When a page is loaded, the browser creates a hierarchy of objects that parallels
the HTML structure of the page. This is called "reflection." Objects of a level
can be considered as properties of the objects in the previous or upper level.
The root object of the hierarchy is the "window" object. It has a child named
"document" and elements such as anchors, forms and images are objects that
descend from "document", their names taken from the name attribute of the tag.
To refer to a specific object (or property), you must specify the object's name
and all of its ancestors. The "window" object may be left out. For example, the
image that appears as the source in this image tag:
<IMG NAME="picture1" SRC="images/bird1.gif">
can be referenced as document.picture1.src. Here "src" is a property of
the object "picture1".
Object Properties and Methods
Besides having properties, an object may have "methods." A method is a
JavaScript function that is associated with an object. The document object has a
method called "write" that is one of the most often-used JavaScript methods. The
reason is that using this method one can build pages with dynamic content (DHTML) because the output of "document.write" is sent to the browser for its
interpretation as HTML code. For example,
<SCRIPT>
document.write("<A HREF='somepage.html'>Link to a page</A>")
</SCRIPT>
has the same effect as writing,
<A HREF="somepage.html">Link to a page</A>
While this may not seem a very impressive feature, you must consider that the string that we give to "document.write" can be built using the value of variables that are taken from the document's environment or that are the result of a user action. For example, we may validate data entered into a form and display a helpful error message to the user.
The document object has, among others, the properties "title" and "URL." They
can be used to print a page footer in the following way:
<SCRIPT>
astring = "This is the page " + document.title + " from "
+ document.URL;
document.write("<P>"+astring+"</P>")
</SCRIPT>
JavaScript built-in objects
Although variables in JavaScript are typeless or, if you prefer, dynamically typed, you can create objects of a given type. Using the object-oriented terminology, what one really does is to create instances of a set of built-in classes.
Instead of declaring a variable of type array, you can create an object of class Array. Similarly, you can create objects of type String or Boolean. These objects, which can be used as variables, have interesting methods and properties.
Array
I will show you how to create an array. The "new" method of the class Array allows me to create an array. The array may be empty or you may altogether specify its elements. You may also skip the "new" operator, which will give the feeling of initializing a variable, but remember that an array is an object. You can do assignments to elements of an array, as you would do with an array variable.
// creating an array with elements
arr1 = new Array("apple","orange","banana");
// creating an empty array
arr2 = new Array(3);
arr2[0] = "apple";
// implicit creation of an array
arr3 = ["apple","orange","banana"];
|
If you want to display the array's elements, you can use the following function that shows the use of the "length" property and the use of subscripts to access elements.
function dispArr( arrarg ){
if (typeof(arrarg) != "object") return false;
var l = arrarg.length;
var i;
for ( i = 0; i < l; i++) {
document.write("<br>" + i + ": " + arrarg[i]);
}
}
|
Boolean
When using Boolean objects, you must remember that the behavior of this class is not what you would expect. To create a Boolean object, you may use any of the following.
// create a false Boolean object
x = new Boolean()
x = new Boolean(0)
x = new Boolean(null)
x = new Boolean("")
x = new Boolean(false)
// create a true Boolean object
x = new Boolean(true)
x = new Boolean("true")
x = new Boolean("false")
x = new Boolean("Humpty Dumpty")
|
Anything that is not a zero, a null, an empty string, or the built-in value false, will give a true value to the Boolean object. If you use a Boolean object with a false value as the conditional expression in an if statement, it will behave as having a true value. To get the real value of a Boolean object, you must use the valueOf method.
Copy and test the following piece of code.
a_false_value = false;
a_bool_obj = new Boolean(false);
if ( !a_false_value ) {
document.write("<p> A false is a false...");
}
if ( a_bool_obj ) {
document.write("<br>...but a Boolean is true.");
}
if ( !a_bool_obj.valueOf() ) {
document.write("<br>Here is the real value.</p>");
}
|
In earlier versions of JavaScript, Boolean objects behaved as Boolean variables do, that is, a Boolean object whose value was false was treated as the primitive value false.
String
The String class can be used to create String objects that behave very
much like string variables. For example, the new operator can
be obviated by assigning a quoted string to the object, as in:
str1 = "The best web site";
The String object has methods to format its value. Let us suppose that you have a function like this one to help writing strings.
function print( str ){
document.write("<br>" + str);
}
|
You can print a string in bold letters, or make it a link, or an anchor.
print( str1.bold() );
print( str1.link("#comehere") );
print( str1.anchor("comehere") );
|
The last three lines would be equivalent to include in your page the following.
<B>The best web site</B>
<A HREF="#comehere">The best web site</A>
<A NAME="comehere">The best web site</A>
|
A string literal can use methods of the String object. They are called using the usual period notation, as in:
print( "Here you are".toUpperCase() );
Strings can be concatenated or split to an array.
str2 = " does not exist.";
print( str1.concat(str2) );
arr4 = str1.split(" ");
dispArr( arr4 );
|
gives the following:
The best web site does not exist.
0: The
1: best
2: web
3: site
Javascript built-in functions
In addition to objects, properties, and methods, JavaScript has built-in functions that are not associated with an object, but are part of the language itself. I am giving here some examples of these functions.
parseFloat and parseInt
The parseFloat function receives a string as its parameter and tries to interpret it as a floating point number. The function parses the string until its end or until the first character that cannot belong to a floating point number. It can therefore do a partial interpretation if an otherwise correct number has, for example, a letter in the middle. When the function cannot make any number out of a string, it returns the special value NaN.
Let us see some examples. All of them should be placed within the <SCRIPT></SCRIPT> delimiters. The code is shown with a gray background. The result of the code is shown in blue color. Note that in expressions where numeric and string values are combined with the "+" operator, JavaScript converts the numbers to strings.
Example 1
var num1 = "12.34";
document.write("<p>Result: "+parseFloat(num1));
Example 2
var num1 = "123A56.78";
document.write("<p>Result: "+parseFloat(num1));
The parseInt function does a similar job, but with integer
numbers.
Example 3
var num1 = "12345";
document.write("<p>Result: "+parseInt(num1));
Example 4
var num1 = "12A45";
document.write("<p>Result: "+parseInt(num1));
isNaN
This is a logical function that can be used to test if any value given to it as a parameter is not a number, in which case the function returns the logical value true. If the value does correspond to a number, the function returns false.
Example 5
var str1 = new String("hoobleydook");
document.write("<p>Result: "+isNaN(str1));
String and Number
These functions perform the job of converting between strings and numbers when this is necessary. Remember that JavaScript is a typeless language and that fewer conversions are needed than in other languages.
Example 6
x = String(12345);
document.write("<p>String : "+x);
document.write("<p>Number : "+Number(x));
Escape and unescape
The escape function performs the job of converting those characters in a string that are not letters or numbers to their ordinal numbers in the ASCII character set. The numbers are expressed in the hexadecimal system and preceded by a percent symbol. For example, a space is converted to "%20". This method is often used to encode URLs and the result is said to be "URL-encoded." The unescape function performs the inverse job.
x = escape("Hello, world #3!");
document.write("<p>escape : "+x);
document.write("<p>unescape : "+unescape(x));
|
JavaScript Events
JavaScript can be used to create event handlers. Each HTML element can be
considered as an object subject to events like the change of a text-box’s
contents or the click of a button. Events receive names like onClick or
onChange. JavaScript functions may be coded to handle these events. Each
element in an HTML page has a set of events associated with it. In the following
examples, I will use the onClick event, which is easily understood
because everyone knows what is to click with the mouse, and can imagine that for
any element is important to know when it is clicked. This event is the way an
element has to know that it has received a click. Each event that JavaScript
allow us to manage has a code name that must be used to tell JavaScript what to
do with the event. This name is included as an additional attribute in the
element's tag, and is assigned the name of a JavaScript function that will act
as an event handler. Supposing that it is an image that we are tracking, the
coding will be:
<IMG SRC="a_nice_image.jpg" onClick="eventhandler">
The string "eventhandler" should be replaced by the name of the function and any parameters that it must receive. We can also place all the function's statements "in-line" between the quotes if it is a small function, but it is better to place it in the HEAD section.
Suppose that you code a function that issues a welcome message to the user. The name of the function is Hi_you(). If you want that the message appears when the user presses a certain button, this could be achieved in the following way using the event OnClick:
<html>
<head>
<title>Hi you page</title>
<script>
function Hi_you()
{
alert("Hi, you!")
}
</script>
</head>
<body>
<INPUT TYPE="button" VALUE="Hello button" onClick="Hi_you()">
</body>
</html>
|
Using the HREF attribute of an anchor tag (A), we would obtain the same result.
<A HREF="javascript:Hi_you()">Click to be greeted</A>
To teach you how to use a parameter in a function call, I will develop a very simple function. This function will do nothing but show you which element has received a click, using a message in the browser's status bar . The function will be able to do this because it will receive a parameter indicating the clicked element. Code the following in the HEAD section of the page.
<script language="JavaScript">
// handles click events for several elements
function message(field){
if (field == 1) {
window.status="You clicked the text box.";
}
if (field == 2) {
window.status="You clicked the text area.";
}
if (field == 3) {
window.status="You clicked a radio button.";
}
if (field == 4) {
window.status="You clicked the check box.";
}
}
</script>
|
In the body of the page, code a form as follows:
<form>
<input type="text" name="textbox" onClick="message(1)">
<br>
<textarea rows=2 cols=20 wrap=virtual name="textlines"
onClick="message(2)">
</textarea><br>
<input type="radio" name="radio" onClick="message(3)">
Option 1<br>
<input type="radio" name="radio" onClick="message(3)">
Option 2 <br>
<input type="checkbox" name="check" onClick="message(4)">
Check Button<br>
</form>
|
Save your work and load the page into your browser. Click any element and look at the status bar.
Click here to view the sample page in a new window.
JavaScript events occur to the majority of the HTML elements in a page, including those in a form. This is useful because you can perform a series of checks on the data input by the user before sending these data to the script in charge of processing them. I will not talk now about the checks you can perform, but on how you can detect different events happening in your form.
An event can be the fact of an element getting or losing focus. An element is said to have focus when it is the one that will receive the next keyboard interaction initiated by the user. The action of giving focus is usually called 'selecting.' Let us say that you are doing an on-line purchase and you must type your credit card number in a text box. You must first select the text box either by clicking it or by pressing the TAB key until a cursor appears in the text box. The result of the selection process is that the text box now has focus.
The event of getting focus is signalled by the event 'onFocus,' and the event of losing focus is signalled by the event 'onBlur.' If you have two routines that process these events, say, 'proc_focus()' and 'proc_blur(),' you may code the tag as follows.
<input type="text" name="textbox" onBlur="proc_blur()"
onFocus="proc_focus()">
Generally, you don't need to process both events; you choose one or the other as you see fits. I will show here an example using two more events, clicking and changing, but no processing will be made except signalling that the event has happened. The events are 'onChange' and 'onClick.' The click event obviously occurs when someone clicks on the text box. The change event occurs when the user commits changes to the element value. It does not fire when the actual changes are made, but rather when the form is submitted or focus is removed from the element.
The functions to process the events are coded in the HEAD section.
<SCRIPT language="JavaScript">
// show messages in the status line
function proc_blur(){
window.status="Blur has happened";
}
function proc_click(){
window.status="Click has happened";
}
function proc_change(){
window.status="Change has happened";
}
</SCRIPT>
|
In the BODY section we will code the form.
<FORM>
Get out of here <INPUT type="text" name="textbox1"
onBlur="proc_blur()"><BR>
Click this box <INPUT type="text" name="textbox2"
onClick="proc_click()"><BR>
Change this value <INPUT type="text" name="textbox3"
value="No value" onChange="proc_change()"><BR>
</FORM>
|
Click on the first box, press TAB, and look at the message in the status line. Click the second box and look at the message. Modify the value of the third box, press TAB, and look at the message. That is all that there is to it. It is now up to you to code the functions to carry out the exact processing that you want for each type of event and each type of element.
Remember that text boxes are not the only elements in a form that can be scripted this way. The events we have seen (click, focus, blur, and change) can also be applied to text areas, buttons, check boxes, and radio buttons whenever it is sensible to do so.
Click here to view the sample page in a new window
Form processing with JavaScript
This example will show how to process the input to a form. The goal is to convert some amount of an undetermined currency to euros. You can choose from a series of conversion factors pre-loaded in a table. This table is implemented as a selection list, where each factor is an option value. A text box is provided to enter the amount to convert, and a button to make the conversion. Once a value is entered (a default value is displayed), the selection of a new conversion factor produces an automatic calculation. I will show first the form.
<form>
<input name="amnt" size="10" value="10">
<select name="curry" onChange="Calc()">
// how much is it in euros
<option value="1.250">1.250</option>
<option value="1.500">1.500</option>
<option value="1.750">1.750</option>
<option value="2.000">2.000</option>
</select>
is equal to
<input name="euro" size="10">
Euros.
<br>
<input type="button" value="Calculate" onClick="Calc()">
</form>
|
The input box is named "amnt" and it is assigned a default value of 10. The output of the calculation is displayed in an input box named "euro". In both cases the default type of "text" is used. The selection list is named "curry", and when it changes, the Calc() function is fired. An unnamed button is defined that when it is pushed executes the Click() function. The form receives no name, and no attributes are included. In particular, neither action nor method is mentioned. The usual submit button is also missing.
The Calc() function is next showed, which should be included in the HEAD section.
function Calc() {
var res = new String;
var atmp = Math.round(
document.forms[0].amnt.value *
document.forms[0].curry[document.forms[0].curry.selectedIndex].value
* 100
) / 100;
res = atmp.toString();
document.forms[0].euro.value = res;
}
|
A String object is assigned to a variable named "res". The "atmp" variable is assigned a large formula that will be broken into pieces. As the form has no name, the "forms" collection must be used to refer to it. It is the only form of the page, so its index is zero. Each control in the form is a property of forms[0]. The value of each control is contained in the "value" property.
The selection list is in reality an array whose elements are the numbers listed as options. The value of each element is again obtained using the "value" property. The list as a whole has a "selectedIndex" property that gives the index of the element currently selected.
The value input by the user is therefore:
document.forms[0].amnt.value
and the value of the selected conversion factor is:
document.forms[0].curry[document.forms[0].curry.selectedIndex].value
As the "round" class method works only on integers, we must multiply and then divide by 100 to get the result rounded to the cent. To convert the numeric result to a string, we use the "toString" method of the String object. This string is assigned to the value of the output box.
You can see that, both by pushing the button and by changing the conversion factor, the calculation is triggered, and the result value is showed. Put the form in the BODY and the function in the HEAD of an HTML page, and make some conversions.
You will notice that the result is presented with only one digit after the decimal point. If you want to show two digits, as it is usual, you can use the following code.
function Calc() {
var res = new String;
var pos;
var atmp = Math.round(
document.forms[0].amnt.value *
document.forms[0].curry[document.forms[0].curry.selectedIndex].value
* 100
) / 100;
res = atmp.toString();
pos = res.indexOf('.');
if ( pos != -1 ) {
res = res.concat("00");
res = res.substr(0, pos+3);
}
document.forms[0].euro.value = res;
}
|
A new variable and three more methods of the String object are used. These methods are indexOf(), concat(), and substr(). They perform the jobs of searching a point, concatenate two zeros, and trim the resulting string. Note that the substr() method extracts a portion of the string that starts at the position given by its first parameter, and the number of characters to extract is given by its second parameter.
Click here to view the sample page in a new window.
Displaying dynamic content
Some years ago a new tool was added to the tool-box used by Webmasters. It was Dynamic HTML, whose acronym is DHTML, and which means the joint use of JavaScript and Cascade Style Sheets (CSS) to achieve some original effects that cannot be achieved using only HTML. Its use entails working with objects and properties. I will show an example of how to display a flashing text banner in a page of your site. This banner will display various messages in a rapid alternation.
The area where the banner will appear will be defined using the DIV tag, and the characteristics of this area (or layer) will be given by means of a style definition in the HEAD section. This section will also contain the JavaScript functions that will take care of alternating the messages.
In the BODY section put the following.
<CENTER>
<div id="content"></div>
</CENTER>
|
The division receives the name of "content". It will serve to give it properties using CSS.
In the HEAD section, put this.
<style type="text/css">
#content {
font-family: Arial;
font-weight: bold;
font-size: 10pt;
text-align: center;
color: red;
width: 80%;
height: 1em;
border: thin solid #000000;
}
</style>
|
The typeface of the text will be Arial; it will be bolded, with a size of 10 points, and will be centered. Its color will be red. The box's size will be 80% of its container and will have a thin border. Its height will be just enough to frame the text.
Preview the page: start your browser and load the page. You will see only an empty rectangle. Now, in the HEAD section add these functions.
<SCRIPT language="JavaScript">
var mycontent=new Array()
var i=0
mycontent[0]='Learn about JavaScript and get free scripts!'
mycontent[1]='Enjoy the best DHTML scripts and components!'
mycontent[2]='Here is your source for CGI scripts!'
mycontent[3]='Links to the best resources on the Web!'
function alternate(){
content.innerHTML= mycontent[i];
if (i==mycontent.length-1)
i=0;
else
i++;
}
function rotate(){
setInterval("alternate()",1000)
}
</SCRIPT>
|
An Array object is created, and it is populated with four phrases. A global variable "i" points to the right phrase to display. The display is made by assigning it to the "innerHTML" property. After this, the pointer is incremented or returned to zero. The rotate function sets one thousand milliseconds as the length of the interval with which alternate should be called.
Preview the page: switch to the browser and refresh the display. There is still only that dull empty box. Turn again to your editor and modify the BODY tag as follows.
<BODY BGCOLOR="#FFFFFF" onLoad="rotate()">
The "onLoad" event-handler is set to rotate. When the page is loaded, the rotation will start. Preview the page again, and now you will see the red text messages alternating inside a black border box.
Click here to view the sample page in a new window.
Previous | Contents | Next
|