CS 120, Fall 2012, Lab 2:
Introduction to JavaScript

JavaScript is a programming language that is used to make web pages active. JavaScript code can be incorporated into HTML files, or it can be in separate files that are linked to the HTML files that use it. This lab is a very basic introduction to just a few of the features of JavaScript. You'll learn how to use JavaScript to program what will happen when the user clicks on a button, and you'll learn some of the things that JavaScript can do to a web page. You will also be introduced to the Web Console in the Firefox web browser.

Assignments for this lab are due at the start of next week's lab. Part of the lab consists of written (or typed) answers to some questions. You should print that out to turn it in. (You can print it in the lab.) The rest of the lab asks you to create web pages, which should be on the web, in the www directory of your Linux account.

JavaScript and the Web Console in Firefox

For the first part of this lab, you will work in the Firefox Web Browser. Firefox has a set of developer tools that can help you with JavaScript programming. (Other browsers, such as Chrome and Safari, have similar tools.) Sign into your Linux account, and open the Firefox browser. Load the following page into the browser by typing the address into the location box at the top of the browser window (or open this page in Firefox, and then click the link):


You'll see a rather useless web page that you will use to do some experiments with JavaScript.

Now, while viewing that page, go to the "Tools" menu in Firefox, then into the "Web Developer" submenu, and select the "Web Console" command. The window will split and you will see the Web Console in the region above the page contents. You will probably see some errors and warnings in the web console, but you can ignore them (or Clear them).

You will be typing JavaScript commands into the Web Console. The input area is a line at the bottom of the console, marked with a ">". Click in that input area so that you can type into it.

For example, type 2 + 2 into the input area, and press return. When you type in an expression like 2 + 2, JavaScript will evaluate it and will put the answer in the top section of the web console. Try typing in Math.sqrt(2) (and press return!) to see the value of the square root of two. And try entering the command alert("Hello"). This will pop up a dialog box that displays the message, Hello, to the user. (This command is not so useful in the Web Console, but it can be useful in JavaScript programs on a web page.) You might also try

prompt("What is your name")

Which asks the user a question and gives back whatever the user types as an answer.

Now, let's start working on the web page. You can actually use JavaScript to make changes to the appearance and content of the web page while it is displayed in the browser. One way to do this—and the only way that we will use in this lab—is to refer to an element of the page by using its id. To do this, an element must have an id="..." attribute in the HTML source code of the page. For example, the first headline on the page is an <h2> element that has id="mainhead" so its id is mainhead. To refer to that element in JavaScript, you can say:


Once you get a reference to an element in this way, there are certain things that you can do it. One thing that you can do is to change the entire content inside the element. You do this by assigning a new value to the innerHTML of the element. For example, the JavaScript command

document.getElementById("mainhead").innerHTML = "Hello World!"

will change the <h2> element to show the text Hello World, just as if it had been written <h2>Hello World</h2> in the first place. Try typing this command into Firefox, and observe the effect that it has on the web page! (You should actually see that the text on the web page has changed. If it didn't change, make sure that you typed the command exactly. The case is significant: You have to enter innerHTML exactly, not innnerHtml.) As you type into the JavaScript console, you'll notice that it sometimes gives possible completions for things that you have typed. For example, if you've typed "do", it will show "document". You can hit the tab key to accept the completion. Also, if there are several completions, they will be shown in a menu and you can click on one to accept it.

It can become tedious to type long references over and over. JavaScript has a way of giving a name to something, so that you can refer to it by a shorter name. This is called a "variable". For example, you could make the variable mh refer to the element with id "mainhead" by saying

mh = document.getElementById("mainhead")

This command is called an "assignment statement," and we say that the value of document.getElementById("main_heading") is "assigned to" mh. After that, you can say simply mh instead of document.getElementById("main_heading). Type the above assignment statement into the Web Console, and test that it worked by entering the command

mh.innerHTML = "Goodbye World"

The text of the heading on the web page should change to "Goodbye World." On the other hand, when you are typing you can hit the up-arrow key to go back to a previously entered command and you can edit the command before pressing return again. This is another way to save typing.

You can also change the CSS style of elements on the web page. For example, the command

document.getElementById("mainhead").style.color = "red"

or (assuming that you've previously entered the above assignment statement)

mh.style.color = "red"

will change the color of the text in the heading to red, just as if the CSS style rule "color: red" had been applied to it. (Remember that when changing style, you must always include the ".style" part of the command, and the value that you assign must always be in quotes!)

Unfortunately, some style properties have different names in JavaScript than they do in CSS. The reason for this is that a name such as "background_color", with an underscore character, is not allowed. To deal with this, leave out the underscore and make the next character uppercase. That is, use backgroundColor instead of background_color. So, to set the background color for the heading to "#DDF", you can use the command

document.getElementById("mainhead").style.backgroundColor = "#DDF"

I will leave you with one more example of using JavaScript to modify a page. The sample page contains an image element with id="facpic". You can, of course, refer to the image element as document.getElementById("facpic"). An image element has a src attribute, which specifies the URL where the image can be found on the web. In JavaScript, you can change the image displayed on the page by assigning a new value to the src of the image element. For example, you can change the source of the image on the sample page by saying:

document.getElementById("facpic").src = "http://math.hws.edu/web/faculty/vaughn.jpg"

Try it! The picture on the page should change. You can change most attribute values in the same way. For example, to make the picture 200 pixels wide, use

document.getElementById("facpic").width = "300"

Assignment 1: Web Console Exercises

The rest of this lab contains three assignments for you to turn in next week. For your first assignment, you will do a few exercises in the Web Console in Firefox. Each exercise asks you to use one or more JavaScript commands to accomplish some task. You should type the commands into the Web Console to make sure that they work, and you should record the commands. (I suggest making a new file in the text editor, gedit, and copying your answers into that document. You can print the document when you are done. You should also save it in your account, to have a copy, but you should not put it in your www folder.)

Here are the exercises. Before you begin, you should reload the sample file, http://math.hws.edu/eck/cs120/f12/lab2/sample.html, in Firefox, so you can start with a fresh page. To do the exercises, you will need to consult the HTML source code for that page. To do that, right-click the browser window that contains the page, and select "View Page Source" from the popup menu. You can see that many elements have id's, including the <body> element, which has id="content". You will have to do some research in the textbook or at w3schools.com to answer some of these questions!

  1. The name of CPSC 120 is egregiously misspelled. It says "CPSC 120: Principals of Computer Science". It should say "CPSC 120: Principles of Computer Science." What JavaScript command can be used to fix the problem?
  2. What JavaScript commands will change the color of the name of the school (id="school") and of the name of the department (id="dept") to red?
  3. What JavaScript commands will change the entire page to be dark blue text on a light blue background? (Note that if you do both #2 and #3, the name of the school and department will still be in red. This is because the rule that makes them red is more specific than the rule that makes the text of the whole page blue.)
  4. The entire computer science section of the page is in a <div> element with id="cs". What commands will show this section with: a light yellow background color, a thin red border, and a 2cm margin on the left?
  5. What command will add a thick black border just to the top of the math section of the page?
  6. What command will center the main heading on the page?
  7. You can make an element entirely invisible by setting the value of its display property to "none". Based on that information, what command will make the math section of the page invisible?

Active Buttons

This is all well and good, but you don't want the users of your page to have to type in JavaScript!! How can you make a web page active by including JavaScript commands in the HTML source itself, and what will the user have to do to execute those commands? One of the simplest way is to use a <button> element. A <button> element adds a clickable button to the page. A <button> can have a onclick attribute. The value of the onclick attribute consists of JavaScript code. The JavaScript code is executed whenever the user clicks the button. The text inside the <button> element becomes the text on the button. For example,

<button>Click Me!</button>

creates a buttonthat says "Click Me," like this: . This button doesn't do anything when it is clicked. To make it do something, you can add an onclick attribute to the button. For example,

<button onclick='document.getElementById("foo").style.color="red"'>
   Use Me!

places a button on the page that will make the element with id="foo" red when the button is clicked. To see this in inaction, click this button: makes the text of the next paragraph red.

For a button to do several things, the onclick property of the button can include several JavaScript commands. That is OK, as long as the commands are separated by semicolons (;). For example,

<button onclick='document.getElementById("foo").style.color="red"; 
   document.getElementById("bar").style.color="blue"'>Show Me!</button>

makes a button that changes the colors of two elements.

Some notes on the syntax: The value of the onclick attribute will often include quote marks. But the whole value must also be enclosed in quote marks. To keep things straight, you must use two different types of quote marks: You can use one pair of single quotes to enclose the entire JavaScript code that makes up the value of the onclick attribute. And you can use double quotes in the JavaScript code. (You could also do the reverse: Double quotes around the entire JavaScript, and single quotes inside the JavaScript.)

The value of the onclick attribute might become quite long. Note that it is legal for this value to extend over several lines in the HTML file. This gets rather ugly, and later we'll encounter a better way to handle this problem.

Assignment 2: Simple Slide Show

For the rest of the lab, you should work on HTML source files in the gedit text editor. Don't forget to save your files into your www folder so that they will be visible on the Web.

For your second assignment, you should create a short, complete web page. The web page is a very simple "slide show." It will display one image, and it will have several buttons. Clicking on any one of the buttons will replace the image with a different image. Each button should bring up a different image.

You should find several images to use on your page. Copy the images into your www folder. To get an image from the web, just right-click the image, and choose the "Save Image As" command, and save the image in your www directory. (Or, you can use full URLs on your page to link directly to images elsewhere on the Web.) If you don't have other images, you can take some from the slide show on the Math/CS Department's main page, http://math.hws.edu. (In any case, make sure that the images that you use belong to you or that you have permission to use them.)

Assignment 3: Style Picker

The final assignment is to make another complete web page with several buttons. Clicking on a button should make several changes to the web page. For example, one button might show the page as white text on a black background with a yellow heading, while another might show dark red text on a light yellow background, and so on. To change the style of the entire page, you should change the style of the body element. (Remember to use buttons where each button does several things! Include several JavaScript commands in the button's onclick attribute, separated by semicolons, as discussed above. Consider using a variable with an assignment statement if you want to make several changes to the same element.)

The web page that you use for this assignment can be original, or it can be one of the pages that you wrote for the previous lab. To reuse a file from lab 1, just copy-and-paste it and rename the copy. (To rename a file, right-click the icon and select "Rename".)

Note that you should try to make your styles look OK!

To complete the lab, you will turn in your
answers to Assignment 1 on paper, and you will
place TWO web pages in your www folder.