Variables, Functions, Objects, and Events
References
- W3Schools JavaScript Variables
- W3Schools JavaScript Functions
- W3Schools JavaScript Objects
- W3Schools JavaScript Events
Introduction
JavaScript uses variables to store information in the computer's memory. A variable is a named storage area, which you can create in your JavaScript code. You often need to store some information in the computer's memory, in a variable, as you do things in the Web page.
Individual lines of code in JavaScript are called statements.
A grouping of statements into a named, logical unit of code is called a function.
JavaScript is object-oriented. An object is a single unit or component that contains functions and variables. The functions in an object are called methods, and the variables in an object are called properties.
Declaring and Using Variables
Now, let's talk specifically about variables. Variables:
- Store information in the computer's memory
- Are created with the var keyword
- When you use the var keyword to create a variable, you are declaring the variable.
- You can assign a value to a variable in the same code that
declares it.
(Please note that the equal sign (=) in JavaScript statements is an assignment operator. It tells JavaScript to assign (transfer) a value to the variable. It is not the same as "equal to" in algebraic formulas.)
For example:var myFirstVar = 25;
var mySecondVar = "Hello!";
- You can also simply declare the variable, like this:
var myThirdVar;
var myFourthVar;
- You can declare more than one variable in the same statement
using a single var keyword followed by a series of
variable names and assigned values separated by commas, like
this:
var myFifthVar = 5, mySixthVar = "Hi!", mySeventhVar = 14.7;
- Have rules regarding how to name them:
- The initial character must be a letter, an underscore, or a dollar sign. Subsequent characters may be numbers, letters, underscores, or the dollar sign.
- The name may not contain spaces.
- Names are case-sensitive. This means, for example, that
- myVariable is not the same variable as
- MyVariable, which is not the same variable as
- MYVARIABLE, which is not the same variable as
- myvariable, etc.
- You must not use any built-in JavaScript keywords, object names, or method names as your variable names. We will see many more of these keywords and reserved names as the course procedes. For now, please note that var, alert, document, write, and function are among those names that you must not use for your variable names.
- Are used in statements throughout your code, either to
receive a value or to transfer a value to another variable.
For example:
var myDog; var myCat; var firstNumber; var secondNumber; myDog = "Fido"; myCat = "Spot"; firstNumber = 12; secondNumber = 37; secondNumber = firstNumber;
Please note these points about variables and statements:
- The equal sign (=) in JavaScript statements is an assignment operator. It tells JavaScript to assign (transfer) a value from the item on the right, into the item on the left, which is usually a variable. It is not the same as "equal to" in algebraic formulas.
- The value assigned to a variable can be a number or a
string (or even a function or an object, but more on that later
in the course).
- A number is a quantity as in normal usage.
- A string is a sequence of characters, enclosed in
quotes.
- A text string must be on a single line in your code. It may possibly display on multiple lines in your text editor, but it must be coded on a single line.
- You can break up a string into smaller pieces, if needed, and then you can "add" (the technical term is "concatenate") them together. We will see concatenation in the "Data Types and Operators" handout.
- You can assign the value in a variable to another variable.
- JavaScript statements end in a semi-colon (;).
Statements, etc.
To review so far:
JavaScript uses variables to store information in the computer's memory.
Individual lines of code in JavaScript are called statements.
A grouping of statements into a logical unit of code is called a function.
You can create new text on a Web page with the write() method or the writeln() method of the document object.
To execute, or run, an object's method, you append the method name to the object name with a period, and include any information that is required to be sent to the method within the method name's parentheses. The information within the parentheses is called a set of arguments.
The write() and writeln() methods of the document object require that you put a text string in the parentheses as the argument. A text string is a sequence of characters enclosed with quotes. The text string that you provide as the argument is used by the write() or writeln() method to put new text into the Web page (document). For example, the code
document.write("How are you today?");
instructs the browser's JavaScript scripting engine to put the text How
are you today? into the Web page at the location where the code resides
within the page's other (HTML and JavaScript) code.
You should note these points about text strings:
- If you need to put a quoted string within a text string, you use
a set of quotes that is different from the outer set, like
this (note the single quotes within the double quotes):
"This string has 'this is a string' in it."
- A text string must be on a single line in your code. It may possibly display on multiple lines in the page, but it must be coded on a single line.
Defining and Calling Functions
A function is a (normally) named set of code that does something. In some other programming languages, a logical unit or grouping of statements is called a procedure. In JavaScript it is called a function.
Functions process information. All function names look like functionName( ). Note that there may or may not be something between the parentheses.
You can write you own functions. When you write your own function, you are defining it. When you use the function in your page, you are calling it.
Here are some things you need to know about writing your own functions:
- Your function must have a unique name for the document (page) you are writing it in.
- Your function may have one or more parameters, which is the term given to any variables inside the parentheses after the function's name. If you have more than one parameter, you must separate the names of your parameters with commas.
- Your function may return a value to the place in the code from where it was called.
Here is a sample of a function:
(Please note that the asterisk in the following code is the multiplication operator, and that the forward slash is the division operator.)
function convertToCentigrade (degFahren)
{
var degCent;
degCent = (5/9) * (degFahren - 32);
return degCent;
}
And it is used in this page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
function convertToCentigrade (degFahren)
{
var degCent;
degCent = (5/9) * (degFahren - 32);
return degCent;
}
var FDegrees;
</script>
</head>
<body>
<script type="text/javascript">
FDegrees = prompt("Type in a Fahrenheit degree to be converted to Centigrade", "");
</script>
<h3>
<script type="text/javascript">
document.write(FDegrees);
</script>
degrees F is
<script type="text/javascript">
document.write(convertToCentigrade(FDegrees));
</script>
degrees C.
</h3>
</body>
</html>
You can see the above code in action here.
You should note these points about calling a function:
- The variables or values that you put inside the parentheses when you call a function are called arguments. (When you are defining the function, these variables are called parameters, as noted above. When you call the function, they are called arguments.)
- A function will not automatically run. You must call the function from somewhere in your page.
- The function must be defined before it can be called. Most programmers put their function definitions in the <head> section of the page, and their function calls in the <body> section of the page, to help ensure that the functions are defined before they are called.
Built-In Functions
JavaScript provides many built-in functions. These functions are available for your use any time you need them.
One handy built-in function is alert( ). You saw alert( ) in
the first section.
The alert( )
function can be used for debugging your Javascript code, too.
Another handy function is prompt( ). The prompt( ) function
asks the user for some
information and then puts that information into a variable that
you specify. You saw prompt() in the sample above.
Microsoft Internet Explorer (IE) has a setting that allows the user to prevent the prompt() function from working. If your prompt() window is not displaying, check this setting:
- Tools
- Internet Options
- Security tab
- Custom level...
- Almost at the bottom of the list, in the "Scripting" section: Enable "Allow websites to prompt for information using scripted windows".
- OK and OK
Here is a sample page that uses prompt(). (The code is shown below:)
<html>
<head>
<title>A Form Letter</title>
<script type="text/javascript">
<!-- hide me
var the_name = prompt("What's your name?", "put your name here");
// show me -->
</script>
</head>
<body>
<h1>Dear
<script type="text/javascript">
<!-- hide me
document.write(the_name);
// show me -->
</script>,</h1>
Thank you for coming to my Web page.
</body>
</html>
Built-In Objects
JavaScript is object-oriented. An object is a single unit or component that contains functions and variables. The functions in an object are called methods, and the variables in an object are called properties.
JavaScript has some built-in objects that programmers use often. One of these objects is the document object. The document object contains information (properties) about the Web page (document) that is currently displayed by the browser. The document object also contains some methods that you can use to modify the displayed document.
As I pointed out above, almost everything that you do in JavaScript involves an object, even if it does not appear to be so. But the object-based nature of JavaScript is clear when you use what is called a built-in object to accomplish a task.
Some of JavaScript's most commonly-used built-in objects are:
- Array
- Date
- Math
- Number
- String
We will look at how these built-in objects are used as the class progresses. For now, look at this short example:
(And please note that the plus sign in the following example is the string concatenation operator. We will see this operator again next week.)
<script type="text/javascript">
var dateStuff = new Date();
document.write("Today's date is " + dateStuff.toString());
</script>
You can see this code running here.
Please note these additional points about the above code:
- Most built-in objects, such as the Date object, require you to create a new copy (technically called an instance) of the object before you can use it.
- Some built-in objects can be used without first creating an instance of it. The Math object is one of these objects. We will see this object later in the course.
Variable Scope
Variable scope refers to where in your program code a variable can be used. The scope can be either global or local.A global variable is one declared outside a function. It can be used anywhere in the code.
A local variable is one declared inside a function. It can only be used inside that function.
Please note that the parameters within the parentheses of a function definition are considered to be local variables inside the function.
Global variables can be very handy. But one rather interesting "feature" of Javascript is that even if you declare a variable inside a function but forget to use the keyword var when declaring it, it is mysteriously created as a global variable.
Here is some code that demonstrates this "feature":
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Declaring Variables</title>
<script type="text/javascript">
<!--
function getNames()
{
the_name = prompt("What's your name?", "");
dog_name = getDogName();
alert(the_name + " has a dog named " + dog_name + ".");
}
function getDogName()
{
the_name = prompt("What is your dog's name?", "");
return the_name;
}
function getNames2()
{
var the_name = prompt("What's your name?", "");
var dog_name = getDogName2();
alert(the_name + " has a dog named " + dog_name + ".");
}
function getDogName2()
{
var the_name = prompt("What is your dog's name?", "");
return the_name;
}
//-->
</script>
</head>
<body>
<div align="center">
<a href="#" target="_blank" onclick="getNames(); return false;">Click here for a survey.</a>
<br><br>
<a href="#" target="_blank" onclick="getNames2(); return false;">Click here for a better survey.</a>
</div>
</body>
</html>
You can see the above code running here.
Events
Events are one of the main ways that JavaScript can make your HTML pages dynamic and/or interactive. An event is a specific circumstance that JavaScript detects, such as a mouse click or a mouse rollover. Mouse clicks and mouse rollovers are called user events.
There are other types of events that JavaScript detects, though, such as the load event, which happens when the page being displayed has completely loaded into the browser.
Here is a list of the events that JavaScript monitors and detects:
| Event | Triggered (happens) When |
|---|---|
| abort | The loading of an image is interrupted |
| blur | An element, such as a radio button, becomes inactive |
| click | An element is clicked once |
| change | The value of an element changes |
| error | There is an error when loading a document or image |
| focus | An element becomes active |
| load | A document or image loads |
| mouseout | The mouse cursor moves off an element |
| mouseover | The mouse cursor moves over an element |
| reset | A form resets |
| select | A user selects a field in a form |
| submit | A user submits a form |
| unload | A document unloads (closes) |
Event Handlers
When an event occurs, your JavaScript code can respond to that event. JavaScript code that responds to an event is called an event handler.
Your event handler code is written as an attribute of the HTML tag that the event occurs in. The general syntax of an event handler is like this:
<HTMLtag eventHandler="Some JavaScript Code">
Event handler names are the same as the name of the event itself, with a prefix of on. For example, the event name for the user's clicking a button element is onclick. Note that the name of the event handler is actually an HTML attribute.
In our example, the tag could be coded like this:
<input type="button"
value="Click Me!"
onclick="alert('You clicked the button!');">
And the above code
looks like this when it is running.
You can put more than one JavaScript statement inside the value of the "event" attribute of a tag. Here is a sample of how to do that:
<input type="button"
value="Click Me!"
onclick="var yourAge = prompt('How old are you?', 'Your Age'); alert('Your age is ' + yourAge);">
And the above code
looks like this when it is running.
HTML Tag Events
Various types of HTML tags have events associated with them. Here is an example of an <input> element in a form that responds to the blur event:
<html>
<head>
<title>Blur Event</title>
</head>
<body onload="document.myForm.textButton.focus();">
<form name="myForm">
<input type="text" value="default text"
name="textButton"
onblur="alert(this.value);">
</form>
<br>
<h4>Click outside the text element, or use the Tab key...</h4>
</body>
</html>
You can see this code running
here.
Please note these points about the above code:
- Both the form and the input tags have name attributes. This attribute allows you to reference the element in your JavaScript code.
- The JavaScript keyword this refers to the element in which it appears. In this code, this appears in the input tag, so it refers to that element.
- The value property refers to the contents of the element.
- The onload event is used to set the initial focus to the text element.
Here is a list of the various types of HTML tags and their associated events:
| Element | Description | Event(s) |
|---|---|---|
| <a>...</a> | Link | click mouseover mouseout |
| <img> | Image | abort error load |
| <area> | Area | click mouseover mouseout |
| <body>...</body> | Document Body | blur error focus load unload |
| <button>...</button> | Button | click |
| <frameset>...</frameset> | Frameset | blur error focus load unload |
| <frame> | Frame | blur focus |
| <form>...</form> | Form | submit reset |
| <input type="text"> | Input Text Field | blur focus change select |
| <textarea>...</textarea> | Text area | blur focus change select |
| <input type="submit"> | Submit button | click |
| <input type="reset"> | Reset button | click |
| <input type="button"> | Generic button | click |
| <input type="radio"> | Radio button | click |
| <input type="checkbox"> | Checkbox | click |
| <select>...</select> | Selection (list box) | blur focus change |
Link Events
When a user clicks on a link, the browser automatically handles the click event and loads the file or document that is referenced in the "href" attribute of the <a> tag. But you can override the browser's handling of the click event with your own code.
In the event handler that you write for the onclick attribute of the
<a> tag, you need to return a value to the browser to tell the
browser what to do with its default handling of the click event.
The two possible return values are:
| return value | what it tells the browser |
|---|---|
| true | perform the default action of opening the URL in the "href" attribute |
| false | do not perform the default action |
Here is some code that uses the click event in an <a> tag:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Click Event in Anchor Tag</title>
<link rel="stylesheet" type="text/css" href="Samples.css">
<script type="text/javascript">
/* <![CDATA[ */
function warnUser()
{
return confirm("This link is only for people with Golden Retrievers!\n\nClick 'Cancel' if you do not love Golden Retrievers.\n\nClick 'OK' if you love them.");
}
/* ]]> */
</script>
</head>
<body>
<div id="mainDiv">
<p>
<a href="GoldenRetrievers.html" onclick="return warnUser();">Golden Retriever Club Home Page</a>
</p>
</div>
</body>
</html>
The above code
looks like this when it is running.
Please note these points about the above code:
- The confirm( ) method returns true if the user clicks the displayed "OK" button. It returns false if the user clicks the displayed "Cancel" button.
- The argument in the confirm( ) method is a string that you can use to give instructions to the user about what happens when they click the "OK" or the "Cancel" button.
- The characters "\n" in the argument in the above code tell JavaScript to put a linefeed (to go to the next line) in the display of the window that confirm() opens. We will see this character sequence many times in JavaScript strings.
- The code in the event handler for the onclick attribute of the <a> tag returns to the browser the value that was returned from the confirm( ) method through the warnUser( ) function.
[ Optional Section ]
Objects
JavaScript is an object-based programming language. This term is intended (by those who think that JavaScript is not a "real" programming language) to communicate the fact that JavaScript is not object-oriented. I regard this distinction as rather artificial, since you are dealing with objects in everything you do in JavaScript. I am comfortable referring to JavaScript as "object-oriented," too.
But the distinction does point up some important differences between JavaScript (which is an interpreted language) and compiled object-oriented languages such as C++ and Java. (The term "compiled" refers to the fact that these other languages require you to transform your program (its source code) into machine language so the computer can run it. The transformation process is called "compilation".)
In a compiled language such as C++ or Java:
- Objects are based on classes. A class is the definition of what an object will contain.
- An object is an instance of a class. You must create (instantiate) an object based on a class before you can use the object.
- You can also create (instantiate) an object based on another, existing, object.
- You can even create your own classes.
In contrast, in an interpreted language such as JavaScript:
- You cannot create your own classes.
- But you can create your own objects, based on existing objects or custom functions called constructor functions.
- Almost everything you deal with in JavaScript is an object or an object's property or method.
- A property is a variable that is contained in an object.
- A method is a function that is contained in an object.
Custom JavaScript objects (objects that you create) are based on functions called constructor functions. In other words, a constructor function is a function that is used to create an object. When you create an object with a constructor function, the object contains, or inherits, all of the properties and methods that the constructor function contains.
An example of a constructor function follows:
function Animal(type, sound, transport_mode)
{
this.animal_type = type;
this.animal_sound = sound;
this.animal_transport_mode = transport_mode;
}
Please note these points about the above code:
- The constructor function's name begins with an upper-case letter. This is not a requirement of JavaScript, but it is a convention used by most programmers.
- The this keyword refers to the object that called the constructor function. In other words, this refers to the object that is being created.
- animal_type, animal_sound, and animal_transport_mode are properties of the object being created.
Objects are created from constructor functions with the new keyword. The following code sample creates a new object called pet from our Animal() constructor function:
pet = new Animal("dog", "woof", "walk/run");
Please note these points about the above code:
- The new keyword tells the JavaScript engine to make some of the computer's memory available to store the object. It also creates the object itself.
- The pet object has three properties: animal_type, animal_sound, and animal_transport_mode.
- To use an object's property, you append the property name to the
object name and put a period between them, like this:
var my_animal_type = pet.animal_type;
An example of some code that uses the Animal object is below, in the "Methods" section of this handout.
[ Optional Section ]
Methods
As I pointed out above, a method is a function that is contained in an object. In a manner similar to how you use it to code properties in a custom function, you use the this keyword to code references to those properties in a custom method.
Here is an example of a method that you could add to the Animal custom object's constructor function:
function displayAnimalProperties()
{
document.write("Type: " + this.animal_type + "<br>");
document.write("Sound: " + this.animal_sound + "<br>");
document.write("Mode: " + this.animal_transport_mode + "<br>");
}
In order to add the above code to the Animal object, you need to add another line to the object's constructor function, too. You would need to add the following line to the Animal constructor:
this.displayAnimalProperties = displayAnimalProperties;
Please note these points about the above two segments of code:
- The this keyword in the method's definition refers to properties defined elsewhere in the constructor function.
- You do not include parentheses after the method's name in the second segment of code. You use only the method's name.
Here is some code that uses the displayAnimalProperties() method:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>A Custom Object -- Animal</title>
<script type="text/javascript">
function displayAnimalProperties()
{
document.write("Type: " + this.animal_type + "<br>");
document.write("Sound: " + this.animal_sound + "<br>");
document.write("Mode: " + this.animal_transport_mode + "<br>");
}
function Animal(type, sound, transport_mode)
{
this.animal_type = type;
this.animal_sound = sound;
this.animal_transport_mode = transport_mode;
this.displayAnimalProperties = displayAnimalProperties;
}
</script>
</head>
<body>
<script type="text/javascript">
var myAnimal = new Animal();
myAnimal.animal_type = "fish";
myAnimal.animal_sound = "blub";
myAnimal.animal_transport_mode = "swim";
myAnimal.displayAnimalProperties();
</script>
</body>
</html>
You can see the above code running here.
Please note these points about the sample code that the above link displays:
- When you create the object with a constructor function
you may, if you wish, use an empty argument list. This
is not the recommended way of creating an object, but you can
do it if you wish. This
is what is happening in the line of code
var myAnimal = new Animal();
- If you do use an empty argument list, however, you will
need to assign values to the object's properties with separate
lines of code. This is what is happening with the lines of code
myAnimal.animal_type = "fish"; myAnimal.animal_sound = "blub"; myAnimal.animal_transport_mode = "swim";
[ Optional Section ]
Inheritance and Prototypes
Objects inherit, or, contain, the properties and methods that are defined in the constructor functions from which they are instantiated. After you instantiate an object, you can assign additional properties to the object, using a period. Look at this code sample:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Adding a Property to an Object</title>
<script type="text/javascript">
function Animal(type, sound, transport_mode)
{
this.animal_type = type;
this.animal_sound = sound;
this.animal_transport_mode = transport_mode;
}
</script>
</head>
<body>
<script type="text/javascript">
var cat = new Animal("feline", "meow", "walk/run");
cat.size = "fat";
document.write(cat.size);
</script>
</body>
</html>
You can see the above code running
here.
Please note these points about the above code:
- When you add a property to an object in the manner shown above, the new property is available only to the object that you have extended, not to other objects that also use the same constructor function.
- You can get around this limitation by using the prototype property, as shown below.
The prototype property is a built-in property that adds a property to an object's constructor function from code that is not actually in the constructor function. Here is some code that adds the size property to the Animal constructor function:
cat = new Animal("feline", "meow", "walk/run");
Animal.prototype.size = "fat";
Any code that follows the code sample shown above, after a new object is created from the Animal constructor function, of course, will be able to use the size property of the new Animal object.
One problem with the above code is that any objects created with the Animal constructor after you have added the size property will have the value "fat", which is probably not what you want. Here is some better code:
cat = new Animal("feline", "meow", "walk/run");
Animal.prototype.size = "";
cat.size = "fat";
horse = new Animal("equine", "neigh", "walk/canter/gallop");
horse.size = "huge";
You can use the prototype property to add methods to an object definition, also. To extend an object definition with a new method, you use the prototype property, followed by the new keyword and the name of the new constructor that you have made.
Here is some code that shows how to extend an object definition with a new method, using the prototype property:
function Animal(type, sound, transport_mode)
{
this.animal_type = type;
this.animal_sound = sound;
this.animal_transport_mode = transport_mode;
}
function WildAnimal(home, food)
{
this.habitat = home;
this.diet = food;
}
WildAnimal.prototype = new Animal();
function FarmAnimal(classification, residence)
{
this.food_group = classification;
this.location = residence;
}
FarmAnimal.prototype = new Animal();
Objects instantiated from either WildAnimal or FarmAnimal will include the three properties from the Animal constructor function, along with the properties specific to each individual object (WildAnimal or FarmAnimal, that is).
The following code instantiates an object from FarmAnimal and assigns all of the properties:
var chicken = new FarmAnimal(); chicken.animal_type = "chicken"; chicken.animal_sound = "cluck"; chicken.animal_transport_mode = "walk/fly"; chicken.location = "barnyard"; chicken.food_group = "poultry";OR
var horse = new FarmAnimal("dogfood","barnyard/field");
horse.animal_type = ""equine";
horse.animal_sound = "neigh";
horse.animal_transport_mode = "walk/canter/gallop";
You can see the above code in a complete HTML page below:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Prototyped Methods</title>
<script type="text/javascript">
function Animal(type, sound, transport_mode)
{
this.animal_type = type;
this.animal_sound = sound;
this.animal_transport_mode = transport_mode;
}
function WildAnimal(home, food)
{
this.habitat = home;
this.diet = food;
}
WildAnimal.prototype = new Animal();
function FarmAnimal(classification, residence)
{
this.food_group = classification;
this.location = residence;
}
FarmAnimal.prototype = new Animal();
var chicken = new FarmAnimal();
chicken.animal_type = "chicken";
chicken.animal_sound = "cluck";
chicken.animal_transport_mode = "walk/fly";
chicken.location = "barnyard";
chicken.food_group = "poultry";
var horse = new FarmAnimal("dogfood","barnyard/field");
horse.animal_type = "equine";
horse.animal_sound = "neigh";
horse.animal_transport_mode = "walk/canter/gallop";
</script>
</head>
<body>
<h4>A horse makes the sound
<script type="text/javascript">
document.write('"' + horse.animal_sound + '".');
</script>
</h4>
<h4>A horse hangs out in the
<script type="text/javascript">
document.write(horse.location);
document.write(".");
</script>
</h4>
</body>
</html>
You can see the above code running here.
[ Optional Section ]
Image Maps
Okay, you should now know enough about events and event handlers to understand the image map sample that we looked at last week. Here is the code:
<html>
<head>
<title>North America</title>
<script type="text/javascript">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
function change_image(image_name) {
document.northAmerica.src = image_name;
}
function reset_image() {
document.northAmerica.src = "north_america.gif";
}
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</script>
</head>
<body>
<img src="north_america.gif" usemap="#northAmerica_map" name="northAmerica">
<map name="northAmerica_map">
<area shape="circle" coords="44,46,20" nohref onmouseover="change_image('alaska.gif'); return false" onmouseout="reset_image(); return false">
<area shape="poly" coords="110,10,144,22,152,60,107,31" nohref onmouseover="change_image('greenland.gif'); return false" onmouseout="reset_image(); return false">
<area shape="poly" coords="62,45,107,23,162,86,125,111,106,100,55,96,49,64" nohref onmouseover="change_image('canada.gif'); return false" onmouseout="reset_image(); return false">
<area shape="poly" coords="60,96,125,105,142,98,134,153,97,155,50,123" nohref onmouseover="change_image('continental_us.gif'); return false" onmouseout="reset_image(); return false">
<area shape="poly" coords="61,135,122,165,109,181,65,159,60,136" nohref onmouseover="change_image('mexico.gif'); return false" onmouseout="reset_image(); return false">
</map>
</body>
</html>
You can see the above code running here.
Please note these points about the image map code sample:
- The name attribute of the <img> tag is used to give you the ability to reference the image by name in your JavaScript code.
- The name is case-sensitive in your JavaScript code. It must match the name in the "name" attribute.
- When you assign an image file name to the src property of an image object, the named image is replaced with the new file.
- The NOHREF attribute of the <area> tags tells the browser not to expect a URL to be associated with this image map area. In other words, this area will not be a link.
[ Optional Section ]
An Alternative to document.write()
So far, a lot of the sample pages in these handouts have used the document.write() built-in method to put JavaScript-generated information into the Web page's display.
There is a major problem, though, with using document.write(): If you use this method after the page has loaded, all of the page's code -- ALL OF IT -- including the HTML tags and any other JavaScript code -- gets wiped out and replaced with only what is written into the page with document.write() after the page has loaded.
Fortunately, there are some alternatives to using document.write(). We will see one of them much later in the course when we talk about jQuery events and effects. And we will see another alternative right now: The innerHTML property, along with the document.getElementById() method.
The innerHTML Property
JavaScript provides a lot of properties about the Web page, which we can use to change what is in the page after the page has loaded. The main property that is used for this purpose is innerHTML.
- The innerHTML property has (contains) the contents of the HTML tag that it represents. These contents can even include other, nested HTML tags, which is why "HTML" is in the name of the property.
- You can get (and assign) the current contents of this property.
- You can also change the contents. Any changes are immediately displayed in the page by the browser.
The document.getElementById() Method
And along with the innerHTML property, JavaScript provides an extremely handy built-in function called document.getElementById(). This method is used to get a "handle" (actually, an object) to any HTML tag which has an id attribute in it.
This powerful combination of method and property is used like this:
- Get or build a string value so it has the desired new contents for the HTML tag that you want to change. You can even put HTML tags into this string value that you are building.
- Assign the value of your string to the HTML tag that you want to change, using the "handle" to the HTML tag which document.getElementById() provides to you.
Here is a sample page which shows how you can use this combination of method and property. This is page ComboSample.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Powerful Method and Property Combo</title>
<link rel="stylesheet" type="text/css" href="Samples.css">
<script type="text/javascript">
/* <![CDATA[ */
function showStuff(newContentsString)
{
document.getElementById("newContentsDiv").innerHTML = newContentsString;
}
/* ]]> */
</script>
</head>
<body onload="showStuff('<h3>The page has loaded!</h3>');">
<div id="mainDiv">
<div id="newContentsDiv">
</div>
<button onclick="showStuff('<h3>You just clicked a button!</h3>');">Click this Button</button>
<button onclick="showStuff('<h3>You just clicked another button!</h3>');">Click this Button, too</button>
</div>
</body>
</html>
You can see the above code running in a browser here.