The Object Hierarchy
We have learned that JavaScript works with "objects." To change the properties of an object (such as size or color), JavaScript needs to be able to refer to the object by using it's full name. This can be is a little confusing at first because the name is constructed hierarchically. That is, in stages. Let's look at a couple of familiar examples of hierarchy before we go on.
A familiar example is a postal address:
President Larry Shinn
101 Chestnut St.
Berea, KY
This means that KY contains Berea which contains 101 Chestnut St. which contains President Larry Shinn. This is an example of a hierarchy. Another example is a URL. What does http://faculty.berea.edu/pearcej/index.html refer to? Well, "faculty.berea.edu" is the name of the computer server, which contains the folder "pearcej" which is a folder on that computer, and which contains "index.html" which is an file in that folder. That's also hierarchical. Each one is inside of another and so on.
The Document Object Hierarchy
We read an HTML document in a window, so everything we see on
the page is part of the window. Inside the window is the
document. Both the window and the documents are examples of
"objects" in JavaScript. As you know, objects have
characteristics called properties
and have methods
for taking actions. We have already seen a method of the
document when we used the document.write()
function. We have also seen a property of the document.
One of the
properties of the document is document.bgColor
which can be used to either report or set the background color.
This "dot" notation is a hallmark of objects.
Every thing in a document can be referenced with JavaScript.For example, we may want to refer to the words or numbers in a text box. First, we need to know which document its on. If it is the current document, it can simply be called 'document'. Now, what HTML Form is the text box in? Well, that's why forms have names, so that you can refer to them by name.
Go check out the example JS-document.html now by trying to change the values of the text boxes.
Let's look at the source:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Using JavaScript to Change the Document Properties</title>
</head>
<body>
<h2>Changing Document Properties</h2>
<hr />
<form id="userinput" action="">
What color would you like this page's background to be?
<input type="text" name="userbg" value="white" size="7" onblur="document.bgColor=document.userinput.userbg.value;" />
What color would you like the text of this page to be?
<input type="text" name="userfg" value="black" size="7" />
</form>
<p><em>(This does not currently work interactively, but you will fix it!)</em><br />
<img src="disk.gif" name="disk" alt="** PLEASE DESCRIBE THIS IMAGE **" id="disk" /></p>
<hr />
<script type="text/javascript">
//<![CDATA[
var d=new Date(); //today
var schoolend=new Date(); //Create a new date and then reset it.
schoolend.setFullYear(2012,4,12); //April 12 is graduation day next year
document.write("Today is "+d+"<br>");
var restofapril=31-d.getDate();
var days=12+restofapril;
document.write("There are only " + days + " more days until summer vacation which will begin on");
document.write(schoolend);
//]]>
</script>
</body>
</html>
In this example, the form has id "userinput" which is inside of the document (Remember that in JavaScript, capitalization matters). So, the form itself is referred to as:
document.userinput
What is the first text box's name, and how do we refer to it? the name of the TEXT box is userbg, which is in the form named userinput which is in the document, so we have:
document.userinput.userbg
Look again at the HTML, and see for yourself. Finally, how do we describe the value which is inside the text box (which is different from the text box itself, which includes a size and a border and such)? This is always called the value. Finally, then, what Is the full name of the stuff inside the text box? It's:
document.userinput.userbg.value
This means the value in the text box named "userbg" in the form named "userinput" in the current document. Note that "value" is not capitalized, and it cannot be.
So, if we want the user to be able to change the
background color to the value a user has typed into this text box, we
can do the following which will set document.bgColor to the value given
by document.userinput.userbg.value:
document.bgColor=document.userinput.userbg.value
Here the value in the left is moved to the place on the right.
This can be done via html by using one of the built-in event
handlers
like:
onblur="document.bgColor=document.userinput.userbg.value;
"
Let's see if you get the idea about he object hierarchy. The image on the page we have been looking at is "disk". Whenever we need to reference an object with JavaScript, we need to be able to refer to it, so we give it a name. This image appears in the document, and we know that their is an image property called "border." How could one refer to the border property in order to reset it to a different number of pixels? Remember to go down in order of biggest to smallest. The 'document' contains the image called 'disk' which contains the property called 'border.' If you considered the following, you were correct:
document.disk.border
The Date Object Hierarchy
The Date object is another example is an important object in JavaScript. The following shows the use of some methods on the Date object in JavaScript:
<script
type="text/javascript">
//<![CDATA[
var d=new Date(); //today
var schoolend=new Date(); //Create another new date.
schoolend.setFullYear(2008,4,22); //May 22 is the last day of finals
this year, we change the value of schoolend to this.
document.write("Today is "+d+"<br>");
var restofapril=31-d.getDate();
var days=22+restofapril;
document.write("There are only " + days + " more days until summer
vacation which will begin on");
document.write(schoolend);//]]>
</script>
If this seems confusing, don't worry--work with the Date Object is not required at this time.
Events and Event Handlers
JavaScript allows us to add interactivity to our webpages. When the user or does something or a page's status changes (such as when it completes loading), an event takes place. JavaScript can detect many of these events through html attributes which start with on" as in onclick, onload onmouseover, etc. In its most basic form, an event handler looks like this:
<a href="a11-function.html"
onclick="alert('I have been
clicked!')">linktonowhere</a>
What happens when the user clicks the link, is that the event handler recognizes the onclick event and calls (or activates) the alert function.
We can also trigger JavaScript events with html forms to create interactivity such as when the user clicks a button:
<form action=""><input
type="button"
value="Click here!" onclick="alert('Thanks for
clicking!');"></form>
Doing something more complicated than poping-up an alert, is
likely to require more than a single line of JavaScript code.
If this is the case, we will need to learn to construct a
Javascript function.
JavaScript Functions
In its most basic form a JavaScript function looks like:
function functionname()
{
statement;
statement;
...
}
We can use a JavaScript function similarly to what we have
already seen. For example the xhtml:
<form action=""><input type="button"
value="Please click" onclick="askname();"></form>
and the JavaScript function:
function askname()
can be used together to run multiple JavaScript statements
after a single event such as a button onclick.
{
var username=prompt("What is your name?","");
alert("Hi "+ username+"!");
}
JavaScript functions are typically defined in the head section
of the xhtml document and enclosed between script tags in the usual way:
<script>
//<![CDATA[
JavaScript is placed here...
//]]>
</script>
We can also take these same ideas and using a form
instead
of using prompt() and alert() by changing the function to the following:
function giveMessage()
{
document.messageform.reply.value=document.messageform.fname.value+", I
hope that you having a good CSC125 class!";
}
Using JavaScript Functions
Here is an example which uses functions to
count the number of clicks of the first button. JavaScript
functions
are necessary here in order to correctly count the number of clicks
because the function needs to be able to be called for each click event
which occurs.
The number of clicks is stored in the variable count which is
declared in the head section as:
var count=0;
Thus, the count is set to 0 on initial page loading,
then when the first button is clicked the following funciton is called:
Clicking the second
button will report how many times you clicked the first
button by displaying the value of count. (Note if you click
the first button really fast, all
of clicks
might not register.)
function add_one()
{
count=count+1;
}
function get_total()
{
document.clickform.result.value="You have clicked the button "+count+"
times.";
}
Then the following form is used to call these functions:
<form id="clickform" action="">
<input value="CLICK ME" onclick="add_one()" type="button">
<input value="GET TOTAL # OF CLICKS" onclick="get_total()"
type="button">
<input name="result" value="" size="40" type="text" >
</form>
Click the first button as many times as you like. Then click
the second button to see how many times you clicked the first
button. (If you click the first button really fast, all of clicks
might not register.
The next example uses a single JavaScript function and several variables to allow the user to play a game.
The Guessing Game
The objective of this game is to guess a whole number
between 1 and 10,
inclusive.
You will get three guesses to guess the number.
(If you wish to start a new game, reload the page.)
For a stand alone copy of the game, click JS-guessing.html. It will be this game you will work with in this assignment
This assignment is to be completed individually. Copy js-guessing.html and resave as yourusername-A11.html. Your task today will be to make this game more fun by giving more feedback to the user about each guess. Even better, I am giving you some choice in how to improve the function to make the game more fun:
As before you want to create a well structured xhtml page which satisfies the following elements of good style:
Save this file as yourusername-A11.html and put this file as well as all of the images used into a folder named yourusername-11, zip and submit to Moodle.
Copyright © 2011 Jan Pearce