CpSc 130 : Introduction to Programming and Information Systems

CpSc 130 Notes Javascript and Dynamic Web Pages


Terms

JavaScript
JavaScript (JS) is an interpreted programming language that can be embedded in web pages. The browser handles running the scripts. Like most scripting languages, JS is interpreted. Theoretically, that means it runs fine up to the point an error occurs. Compiled languages use a special program to analyze your source code and change it into something that can run on the machine. Examples are Java and C++. In practice, a browser may notice and report errors in the JS as soon as the page loads.
web applications
This is just another name for a program that sits on a web server waiting for someone to use it. We used web apps with two of the forms we developed in chapter 13 of Head First HTML. The author uses web apps and forms with many examples.
typical structure
As noted, most of the JS code will be inside a <script> element, which is itself contained in the document <head> element. The rest of the JS will typically appear as the value for an event that can occur.
events
Events are unpredictable. They include mouse clicks (onClick), when a page loads (onLoad) and when a form is submitted (onSubmit), although there are many more. The point of being an event is that we don't know when or in what order the events occur. That makes programming challenging.
onClick
We already know what happens when a user clicks on a link (anchor). We can specify what is to occur for other elements using the onClick attribute. The action to be taken is specified as the value (a string) of this attribute. The string will generally consist of a single JS function call, but may include more JS.
onLoad
This attribute is part of the <body> tag. The event occurs as soon as the page finishes loading. Specify as described for onClick.
onSubmit
This attribute is part of the <form> tag. The event occurs as soon as the user clicks a submit button. Specify as described for onClick.
functions
For now, you can think of functions as a macro, one of the ExcelTM equations or the square root button on a calculator. Typically, you provide one or more values and the function performs some action and gives you some kind of answer. (Not all calculator buttons take input — clear and +/- don't.) JS allows you to use a wide variety of built-in or premade functions and to make your own.
alert("messageText");
A built in JS function that allows you say something to the user by popping up a dialog box with the messageText displayed. This is commonly done for errors, but we will use it extensively, especially for debugging.
getElementById("elementId")
A built in JS function that lets us get (retrieve) an element in the current page, including its current value. We will be using this immediately to access the values of elements you provide a unique id for.
string
A list of characters. We have been using them extensively as quoted text. User input is also received this way – we will have to convert them to numbers, if necessary. The quotes may be either the double (") or single (’) quotes. The trick is to make sure you alternate quotes "don't" try to single quote something with an apostrophe in it or vice versa.

Examples & Discussion

It is traditional in programming languages to first write a program that simple says "Hello world" when it is run. Part of the reason for this is to (hopefully) succeed at making the program do what we want. (That's a bit like making HTML format a page the way you want.) The other reason is to see how difficult or easy it is.

Of course, we can make a web page that says "Hello world" using HTML easily, but our goal is to use JS to make a web page say it without simply coding it in HTML.

The code shown has nothing in the body. It is a file with no real HTML content. Everything we need to do is provided in the body tag itself.

The onLoad attribute specifies that when the event page-is-finished-loading occurs, the JS interpreter should interpret the code provided as its value: alert("Hello world!");
Note that this value was provided as a 'string'.

The alert() function expects to be given a string of text to show the user. Note that the text is provided as a "string" inside the function's parenthesis. The text is called an argument (or a parameter). They are used to pass information to a function.

hello1

<html>
<head>
	<title>Hello World</title>
</head>

<body onLoad='alert("Hello world!");'>

</body>
</html>
    

Since the onLoad string value is given in single-quotes, there can be no single-quotes in the enclosed JS. Usually, this presents no problems since we have been using double-quotes most of the semester, but watch for apostrophes!

Also, notice the semi-colon. It serves as an end of statement marker.

Automatic semi-colon insertion refers to a cool trick used by some JS programmers. When a browser notices that you appear to have ended a JS statement by simply going to the next line, it inserts a semi-colon for you. Very bad practice. We don't want the browser deciding for us. Always use semi-colons.

Here I use the onClick event with two different elements. <strong> is an inline element that can contain any amount of text. The <h2> is a block element.

Notice that using onClick does not make an image or text show as a hyperlink (anchor), because it is not. The cursor doesn't even change to indicate the text is clickable (unless we tell it to).

hello2

<body>
    <h1>Sample onClick web page</h1>
    <p>To see results 
    <strong onclick="alert('Hello world');">
    click me</strong> now.</p>
    <h2 onclick="alert('Now we are having fun');">
    Click me too!</h2>
</body>
    

Note that the roles of single- and double-quotes are reversed here. Also, try clicking anywhere on the line of the block element, as opposed to the inline element.

The example in Figure 4.1 uses onmouseover and onmouseout and these operate as you would expect.


Buttons
getElementById
  <head>
    <title>Mystery Image </title>
  </head>
  <body>
    <img id="myImage" src="redball.gif">
    <input type="button" value="Do it!" onclick="document.getElementById('myImage').src='bullet.gif'">
  </body>
  
Try it. Use these images:
and
and type in the code to the left. It will look like:

Let's decypher the above example.

  1. The img tag has been given an id of myImage
  2. The input tage is of type button and produced a clickable button on the page
  3. The value in a button is the words on the face of the button
  4. When the button is clicked, the getElementById function is called and the tag with the id of "myImage" is located.
  5. The image source (src) is changed from what it was to bullet.gif

document.getElementById() looks up an element in the current page that has the id specified as its argument ("myImage").

The .src (dot-src) specifies that we are interested in the src attribute of the element we just looked up. Note that there are no spaces – this is one long variable name.

We know that the src attribute of the <img> element gives the name of a file to display. What happens if you change it? The new image is displayed!


innerHTML attribute
  <body>
    Welcome to my page
    <input type="button" value="Do it!" onclick="document.getElementById('myText').innerHTML='I changed the text!'">
    <div id="myText">
	There is nothing here of interest
    </div>
  </body>

  
Welcome to my page
There is nothing here of interest

Let's decypher the above example.

  1. The button face has the text "Do it!"
  2. When the button is clicked, getElementById looks for the id "myText"
  3. The innerHTML of the div named "myText" is set to 'I changed the text!'
  4. Again notice that nesting of quotation marks uses single quotes inside of the double