STAR Early College High School @ Erasmus
Internet Seminar: Creating Interactive Web Pages



Week 3 : JavaScript - Part I
Show and Tell

HTML and JavaScript

From studying a little bit of HTML, it's clear that webpages created using only HTML are static -- they don't change over time. That makes sense: HTML is a language that primarily describes the structure or layout of a page:
headings, lists, tables, paragraphs, links, images.
Of course, it includes some text formatting features, too, like bold, italic but even these are static features. Static pages are also passive in a sense — the user just reads them and may or may not really get their heads involved.

So, many people want to create dynamic or interactive pages that can change in response to the user. Many possibilities:

CGI, ASP, Dynamic HTML, Java applets, JavaScript We're going to do some work with JavaScript in this class; it's the best choice for us for a number of reasons:


Programming and Algorithms

Before we actually start talking at JavaScript, let's talk about some general ideas from programming that we'll have to keep in mind

First, if we look at an example of JavaScript (click here), we see that it has some resemblance to English -- it's certainly readable by humans, at least. This presents a problem: can computers understand this piece of text? No, not really: they can execute instructions, but only a very limited set of instructions in very very specific form (in fact, computer instructions are just sequences of 0's and 1's.

So, we type in this JavaScript program which we can read, but the computer only understands 0's and 1's. So how is the computer able to execute our program?

There are essentially two answers to this question:

  1. Some programming languages are compiled. That means that after we type in our program in some language (like Java or C), a special piece of software called a compiler translates our program into the equivalent computer instructions.
  2. Other programming languages (such as JavaScript) are interpreted. That means that when we type in our program, it is translated into computer instructions as needed. With JavaScript, the web browser you use interprets any JavaScript that's on the page when it's loaded.


"GUI" Programming and Events

Let's focus a little more on the kinds of things that our JavaScript programs might do.

JavaScript programs have to respond to the user: moving the mouse, clicking things, maybe typing some stuff into boxes, etc. Programming that is done to work in this context is usually called Graphical User Interface programming, or GUI programming. Most JavaScript programming has this flavor.

First we will need to learn how to include buttons and text boxes on a web page. That involves more HTML tags.

In a GUI setting, the program generally waits for the user to tell it what to do (by, say, pressing a button or clicking a mouse). These actions are called events. After we learn how to create buttons and text boxes, we will learn how to use JavaScript to respond to events.


Syntax

What's syntax?  It's the rules about the punctuation, spelling, etc. that a program must follow -- it's just like grammar, only computers are even pickier than any grammar teacher you can imagine.  One of the most frustrating things about programming (particularly when you're starting out, but it doesn't get any better, really) is having to follow exactly many many rules about formatting and punctuation.

Here's a simple example.  There's a very small mistake in this script -- a missing quotation mark. This kind of pickiness is a pain.  Fortunately, there are some tools available that help you catch at least some of these mistakes. 

For Firefox: In your browser, open a new page and type in the location area javascript: (don't forget the colon).  This opens a new window called the JavaScript console; in this window your browser will provide some information about JavaScript errors.  When you're working on JavaScript assignments for this class, you'll probably want to keep the JavaScript console open all the time. (Another note: depending on how your browser was set up, it's possible that the javascript console will automatically appear every time there's an error; if this happens to you, you're in luck, as far as this class goes.)

For Internet Explorer: If there are JavaScript errors on the page, a small ellow triangle appears on the lower left of the screen. You can click on it to "show details" and get more information about the error.

So far, we haven't actually written very much JavaScript, but already there are a number of important rules to be aware of:


JavaScript Example 1 (alert)

Let's start with a simple example. First click here to see what it does.

If we look at the source of that page, we would see this:


<html> 
<head> 
<title> JavaScript Example 1
</title> 
</head>
<body> 
This is the first line of text on the page. < /br>
<script type="text/javascript"> 
	alert("hello!");
</script> 
This is the second line of text on the page.
</body> 
</html> 

The file is a regular HTML file, with a JavaScript program stuck in the middle of it.

First notice how the JavaScript is inserted -- using the HTML tag pair <script> and </script>

Now let's look at what the script does. The script consists of one line only, which says

	alert("hello!");
alert is a function that direct the browser to pop up a little window with a message. The message displayed in the window will be whatever message you included in the parentheses.

In general, you can say

	alert(" your message goes here ");
and whatever message you specify will be displayed.

Notice that the words of the message are contained in quotes, but that the quotes will not appear on the screen when the alert box pops up.

Watch out for proper punctuation. You must use open and close quotes around the message.


Exercise 1:

Write an HTML page that contains a JavaScript alert to say:   Thanks for visiting my page

JavaScript Example 2 (prompt and alert)

JavaScript becomes interesting when it can respond to user input.

Click here to see the next example.

Here is the source:




<html> 
<head> 
<title> JavaScript Example 2 
</title> 
</head>
<body> 
This is the first line of text on the page. < /br> 

<script type="text/javascript" language="JavaScript"> 

	name = prompt("Please enter your name:");
	alert("hello " + name );

</script> 

This is the second line of text on the page.

</body> 
</html> 

There is a new function used in this example,
prompt
. prompt is a function that directs the browser to pop up a little window with a prompt and an input box. The prompt displayed in the window will be whatever message you included in the parentheses.

In general, you can say

	prompt(" your prompt goes here ");
and whatever prompt you specify will be displayed.

You can also supply a default answer, so that the user can just click on "OK". Click here for an example. To get this effect, you specify a second parameter for prompt:

	prompt(" Enter your answer: ", "yes");
will create a prompt that says Enter your answer: and has the input box already filled in with the answer yes. The user can choose to click "OK" or to change the answer by typing over it.

Notice that each parameter is enclosed by quotation marks and that there is a comma separating the two parameters.

What happens to the answer that the user types in? Usually the JavaScript program will need to use that value to control what the program does. We save the input value by storing it in a location in memory called a variable. The statement

	name = prompt("Please enter your name:");
causes the browser to display a prompt, and then takes the answer from the input box and stores it in a variable called name. We say that name is assigned the value.

In this example, we use the input value to issue a customized welcome message. The next line of the program is

	alert("hello " + name );
The + is used to concatenate, or join, two character strings. "ab" + "cd" is the string "abcd".

What is the difference between

"hello" + "there" and "hello " + "there"?

The first one will result in hellothere; the second will give hello there. A blank counts as a character!

Going back to our example, notice that the word hello is in quotes, but the word name is not. That is because hello is to be treated as a constant value. name is the name of a variable. We don't want to display the word "name"; we want to display the value that is stored in the memory location called name.

More on quotes

Quotes are used to tell the JavaScript interpreter that a particular sequence of text is a string, and that it should be treated as one unit,  not meant to be understood in terms of what it actually says. In fact, if we made a spelling mistake and typed
alert ("Hello theer");
then the words Hello theer would be displayed on the screen. Even though this is a spelling error, JavaScript does not complain.  However, if we try this statement
aletr("Hello there");
then we would get an error message (why?  what's wrong with this statement?).

Clearly, JavaScript treats these two spelling errors very differently.  The second spelling error will cause JavaScript to produce an error message because it violates the rules of JavaScript syntax -- the rules that describe the format of acceptable JavaScript programs.   In this case, aletr is not a command that JavaScript can understand, so we get an error message. Because this error is caused by our violation of the rules of syntax, it is called a syntax error.  The first spelling error is not a syntax error, though, because the quotes tell JavaScript that it doesn't need to worry about what the text actually means.


Exercise:

Write an HTML page that displays a prompt asking What is your favorite sport? and then responds with Baseball is my favorite sport too (Baseball should be replaced with whatever the user happened to type in.)

JavaScript Example 3 (prompt and document.write)

Click here for the next example.

Here is the source code:


<html> 
<head> 
</head>
<body> 
<script type="text/javascript" language="javascript"> 

	alert("Hello. Thanks for looking at my page.");
	yourname = prompt("Enter your first name.");
	document.write("Now I know your name is " + yourname );

</script> 
</body> 
</html> 

The first two lines you're familiar with already. The new thing here is that the script is using the input to write on the Web page itself, rather than responding to the user through an "alert" box.


Exercise:

Write an HTML page that displays a prompt to ask
What day is it today?
and then displays a Web page that says

Today is Tuesday. Have a nice day!

(Tuesday would be replaced with whatever the user happened to type in.)

NOTE:

  1. Do not use an alert box for this exercise.
  2. The message should be displayed as a header on the Web page, using <h2> and </h2>
  3. The day of the week should be displayed in italics.
  4. Remember that the message displayed by the instruction document.write can include text and HTML tags.

Fourth example: ex4 (prompt and document.bgColor) In the previous example, we saw that JavaScript can be used to generate the text of a Web page. JavaScript can work with all of the elements of a Web page, not just the actual text that is diplayed. We can use JavaScript to make the page's display change dynamically in response to the user.

Click here for the next example.

Here's the source:

<html> 
<head> 
</head>
<body> 

This is just some text that might be on the page.
<br /> 

I hope you are enjoying this.
<br /> 

We are going to have fun with it.


<script type="text/javascript"> 

	color = prompt("Choose a color (red, yellow, blue):")
	document.bgColor = color;

</script> 
</body> 
</html>