CS 120, Fall 2011, 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 JavaScript console in the Google Chrome web browser.

Assignments for this lab are due immediately before the start of next week's lab. Remember that the instructor automatically has access to work that you do in Aptana Studio in your Linux account.

Note: Publishing Your Work on the Web

Once I have collected the homework for a given week, you will probably want to publish your work on the web. (Remember that you should never publish your work before I collect it!)

Go to your "Home Folder" in the "Places" menu, which you can find in the bar along the top of the screen. The work that you do in Aptana Studio is in a folder named "Aptana Studio 3 Workspace". If you open the folder by double-clicking it, you will see the project that you created for Lab 1, and if you open that folder, you will see the files that you created for the lab.

Now, open your "Home Folder" again, from the "Places" window. You will see another folder named "www". Anything that you create inside the www folder — or copy into that folder — is visible to everyone in the world on the World Wide Web. You can simply copy files from the "Aptana Studio 3 Workspace" folder into the www folder.

Copy your Lab 1 folder into the www folder. To do this, it's easiest to use copy-and-paste: Right-click the original folder, select "Copy". The right-click inside the www folder and select "Paste." (Note that if you simply drag the folder, that will move it, not copy. You want to be sure to copy it! If you drag it with the middle mouse button — that is, by holding down the scroll wheel as you drag — you get a chance to say whether you want to copy it or move it.)

To see your work on the Web, you just have to know the URL where it is located. If you user name is, say, zz9999, then the contents of your www folder are visible at this URL:

http://math.hws.edu/~zz9999

Just enter this into the location box of a web browser. Note that there is a squiggle ("~") in front of the user name; this character can be found on the upper left key of the keyboard. If the name of your Lab 1 folder is lab1, then the following URL will take you directly to the contents of that folder:

http://math.hws.edu/~zz9999/lab1

And if the Lab 1 folder contains a file named AboutMe.html, then the direct URL for that file would be:

http://math.hws.edu/~zz9999/lab1/AboutMe.html

Some notes:

  1. If a folder on the web contains a file named index.html, then the URL for that folder will actually show the index.html file. If there is no file named index.html, then the folder URL shows a list of files in the folder, and each name in the list is a link to the file.
  2. Spaces and funny characters in file names can cause problems on the web. Stick to simple names, using letters, digits, hyphens (-) and underscore (_).
  3. Make sure that file names have appropriate extensions, such as .html for HTML files.

Review: Picking out Elements: id and class

One of the things that JavaScript can do is to make changes to the elements that make up a web page. Recall that an element consists of a tag (such as <h3>), a matching end tag (such as </h3>), and everything in between them. So the HTML code <h3>Have a <em>great</em> day</h3> is an element, and it contains a shorter element, <em>great</em>, nested inside.

In order to use JavaScript to make changes to a web page, you have to have some way of picking out the elements that you want to change. One way to pick out one particular element is to use an id attribute in the element. For example:

<h2 id="main_heading">Welcome to My Page</h2>

Here, the id main_heading is applied to the <h2> element. The point of an id is to pick out one unique element, so you should never use the same id more than once in the same document. Don't use spaces or special characters in an id. You can safely use letters, numbers, hyphens, and underscore characters.

Sometimes, instead of wanting to pick out one unique element, you want to be able to pick out an entire group of related elements. For that, you can use the class attribute. You can use the same class attribute for as many elements as you like in one document. For example, you might have both <h3 class="bio">My Life</h3> and <p class="bio">I was born...</p> in the same HTML document.

The id and class attributes can be used in both JavaScript and CSS to pick out elements on a web page. In this lab, you'll see how to use them in JavaScript.

Chrome's JavaScript Console

It's time to do some work. For the first part of this lab, you will use Google's Chrome web browser. Chrome has a nice set of developer tools that can help you with JavaScript programming. Sign into your Linux account, and open the Chrome browser by selecting it from the "Applications" / "Internet" menu. (For the first part of the lab, you will not need Aptana Studio.) Load the following page into the browser by typing the address into the location box at the top of the browser window:

http://math.hws.edu/eck/cs120/f11/lab2/sample.html

You'll see a rather useless web page that you will use to do some experiments with JavaScript. Chrome's menus can be found under a small "monkey wrench" icon next to the location bar. Click the wrench, then the "Tools" command, and you'll see a submenu containing, among other things, the command "View Source." Select this command to see the HTML source of the web page. Note that several id and class attributes are used on the sample page.

Now, go back to viewing the web page itself. Select the "JavaScript Console" command from the "Tools" menu. This will open up an area at the bottom of the browser window where you can experiment with JavaScript. (Later, you'll also use it to help you find errors in JavaScript programs that you have written.) You'll see a "<" prompt, with a blinking cursor. You can type in JavaScript statements and expressions at this prompt. For example, if you type in 2+2 and press return, the value of the expression 2+2 will be printed. Try typing in Math.sqrt(2) 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 JavaScript Console, but it can be useful in JavaScript programs on a web page.)

Now, back to id and class... Suppose that there is an element on a web page that has id="main_heading". Then in JavaScript, you can refer to that element as:

document.getElementById("main_heading")

Once you have a reference to an element, 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("main_heading").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 Chrome's JavaScript console, 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.) 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 right-arrow key to accept the completion. Also, if there are several completions, hitting the tab key will cycle among the possible completions. Also note that hitting the up-arrow key will take you back to previously typed lines.

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 "main_heading" by saying

mh = document.getElementById("main_heading)

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 JavaScript 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."

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

document.getElementById("main_heading).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.)


The class attribute is similar to id, except that several elements can have the same class. This means that when you pick out elements using a class, you don't get a single element. Instead, you can an array of elements. (An array is a numbered list.) For example, the sample document has two elements with class="subhead". You can obtain an array containing those two elements, and assign that array to the variable subheads by saying

subheads = document.getElementsByClassName("subhead")

In this case, subheads refers to a list of two elements. You can refer to the individual elements in that list as subheads[0] and subheads[1]. (Computer scientists tend to number things starting with zero rather than one, so that the first item in an array is item number zero, and the first item in the array subheads is subheads[0]. For the same reason, subheads[1] refers to the second item in the array.) You can use subheads[0] and subheads[1] to change the innerHTML or style of the elements. For example, try these commands in the JavaScript console:

subheads = document.getElementsByClassName("subhead")
subheads[0].innerHTML = "Mathematics Courses"
subheads[1].style.color = "#00AAAA"

to change the content of the first headline to "Mathematics Courses" and the color of the second headline to an attractive blue-green.

There is one other command that picks out an array of elements, without any need to use the class attribute: document.getElementsByTagName("tagname") returns an array that contains all the elements in the document that have <tagname> as their start tag. For example, the sample document contains eight <li> elements. You can turn the third one of these red by saying:

elems = document.getElementsByTagName("li")
elems[2].style.color = "red"

(Actually, you could say directly document.getElementsByTagName("li")[2].style.color = "red", if the very long way of referring to the color doesn't confuse you.)


I will leave you with one more example of using JavaScript to modify a page. The sample page contains an image with id="facpic". You can, of course, refer to the image element as document.getElementById("facpic") — or as document.getElementsByTagName("img")[0]. 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:

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

or simply

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

Try it! The picture on the page should change. One final note: In case it's not clear, you can make up just about any name you want for a variable such as pic in the above example. There are a few rules, but for now as long as you stick to names made up of letters only, you should be ok.

Assignment 1: Console Exercises

The rest of this lab contains three assignments for you to turn in next week. You should start up Aptana Studio and start a new project named "Lab2". (Use the "File" / "New" / "Web Project" command. Please be sure to use the name "Lab2" exactly, with no space in the name; this will make it possible for me to find your work.) Create a new file named "assg1.txt" to hold the answers to the first assignment. This will be a plain text file, not an HTML file.

For your first exercise to hand in, you will do a few exercises in Chrome's JavaScript console. Each exercise asks you to use one or more JavaScript commands to accomplish some task. You should type the commands into the JavaScript console to make sure that they work, and you should record the commands in the text file "assg1.txt".

You will need to know a little more about changing styles in JavaScript (and you might need to wait until we have covered some things in class to complete all the exercises.) If elem refers to an element, you have already seen that elem.style.color refers to the color of the text in that element. Similarly, elem.style.backgroundColor refers to the background color of the element, and you can assign any color value to it.

Some style properties have values that are lengths, such as "4in", "1cm", or "20px". Examples include elem.style.width for the width of the element itself and elem.style.marginLeft for the width of the margin on the left side of the element.

The property elem.style.border tells what type of border is drawn around the element; elem.style.borderTop tells what type of border is drawn along the top of the element. These properties have complicated values such as "thick solid black" and "thin double #00AAAA".

Here are the exercises. Before you begin, you should reload the sample file, http://math.hws.edu/eck/cs120/f11/lab2/sample.html, in the Chrome browser, so you can start with a fresh page. To do the exercises, you will need to consult the HTML source code for that page. Remember to record your answers in the text file, "assg1.txt."

  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 name of the school (id="school") to red and the name of the department (id="dept") to blue?
  3. 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 (#FFFFDD) background color, a thin red border, and a 2cm margin on the left?
  4. What command will add a thick black border just to the top of the math section of the page?
  5. There are six elements on the page with class="course". What commands will show the third of these elements in green on a light green background?
  6. What commands will set the entire body element to have a light gray background and a width equal to 600px?
  7. What command wil center the main heading of the page? (For this one, you'll have to do some research to find out the appropriate style property and value.)
  8. Think of something else that you can do to the sample page with JavaScript. List the commands that you used, and describe the effect. (Originality counts.)

Active Buttons

This is all well and good, but how can you make a web page active by including JavaScript commands on the page itself? 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!
</button>

places a button on the page that will make the element with id="foo" red when the button is clicked.

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="red"'>Show Me!</button>

makes a button that changes the color 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, work in Aptana Studio, not in Chrome.

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.

You should find several images to use on your page, and include those images in your Aptana Studio Lab2 project. 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.)

To get an image from the web, just right-click the image, and choose the appropriate command, such as "Save Image As." Save the image on your computer, then copy-and-paste the image into your Aptana project. If you have any trouble doing this, ask for help.

Remember that for an image in the same directory as the web page on which it appears, the src of the image should be a "relative URL" consisting only of the name of the image file, such as "mypic.jpg".

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 entire 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.

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 from the Lab1 project into the Lab2 project in the Aptana Studio window.

Note that all the styles should look good!