CSCI 102T
The Socio-Techno Web
Home
| Calendar
| Labs
| CS@Williams
Lab 5: Introduction to JavaScript
For this week's lab assignment, you will learn about using
JavaScript
to add intelligence and advanced functionality to your web pages. In particular,
in this lab you will learn about Javascript variables, as well as the prompt(),
alert(), and write() functions.
We will continue to learn more about JavaScript in the upcoming weeks.
Note: Some of this lab is based on content found in Chapter 1 of
JavaScript &
jQuery: The Missing Manual, Second Edition by David Sawyer McFarland.
Background Info
Start by reading the selected pages of the Introduction
and Chapter 1
from the book JavaScript & jQuery: The Missing Manual (whole book)
by David Sawyer McFarland. It is highly recommended that you go back and read these chapters closely at a later
time. For now it is ok to read quickly and then move on to the programming parts of the lab.
As we have seen before, the Web is a great resource for learning more about JavaScript. If you want more info about
JavaScript, this tutorial should be helpful.
Exercise 1
- Download the file hello.html by Control+Clicking on the filename and choosing "Save Link As."
Save the file to your www directory. You should also save site.css to your www directory in the
same way.
- Open hello.html in a text editor (i.e., TextWrangler).
- Click in the empty line just before the closing </head> tag and type:
<script>
This code is HTML, not JavaScript. It tells the browser that the text following this tag will be JavaScript.
- Press the Return key to create a new blank link, and type:
alert('hello world');
You've just typed your first line of JavaScript code! The alert() function is a command that pops open an Alert
box and displays the message that appears inside the parentheses. Notice the punctuation used (parenthesis, quotes,
semicolons). This punctuation is very important. We'll discuss this in detail later.
- Press the Return key once more, and type:
</script>
- Save the page. Open the page in a web browser and see what happens. If you don't see an Alert box, you probably mistyped something.
Double check your typing, and ask your instructor for help if you can't figure it out. Also see the note at the bottom of this
page about using the Error Console to debug your code.
- Click the Alert box's OK button to close it.
Exercise 2
- Now we will look at an example that prints a message directly to the web page using the document.write() function.
Download the file hello2.html by Control+Clicking on the filename and choosing "Save Link As."
Save the file to your www directory.
- Open hello2.html in a text editor (i.e., TextWrangler).
- While <script> tags usually appear in the <head> of a web page, you can also put them in the
<body> of the page. Directly below the line "<h1>Writing to document window</h1>", type:
<script>
document.write('<p>Hello world!</p>');
</script>
Like the alert() function, document.write() is a JavaScript command that literally writes whatever you place between
the opening and closing parentheses to the webpage containing the script. Note that
using document.write() after an HTML document is fully loaded deletes all existing HTML.
Thus document.write() is most often used for testing.
- Save the page. Open the page in a web browser and see what happens.
Exercise 3: Mad Libs
In this final exercise, we are going to use JavaScript prompts and variables to make our own Mad Libs game.
(If you aren't familiar with Mad Libs, spend a few minutes learning about them.) In general, a user will be presented
with windows, where they will input text, which will then be put into a premade story with some missing words.
Here is an example.
- Now that you’ve seen an example, start off by making a new webpage in your www directory called madlib.html, and writing your initial tags (html, head, title, body)
along with their closing tags. You may want to link to your CSS file for consistent formatting.
- Normally, JavaScript is put
between the <head> and </head> tags in order to have
the script run by the browser before any other code, however, for this example we will put it directly in between the
<body> and </body> tags.
Start your script with the following line:
<script language="JavaScript" type="text/javascript">
- You will probably want to define some variables to store your data, whether it be text or a number.
(You can read more about variables in Chapter 2 of this book.
Note that although you probably don't need to read this chapter to complete this exercise, you should go back
and read it later.) To create a variable in Javascript, you simply add this line:
var adjective;
"var" is used to define a variable, and as you may have guessed "adjective" is the
variable’s name in this case. Variable names can only be used one time
each in a script, meaning you cannot have two variables named "adjective." The
exception to this rule is that variable names are CaSe SeNsItIvE, meaning
capitalization matters, especially in calling the variable’s contents at a later time.
You will probably want to use a variable to describe each value entered by the user.
- After you have created your variables, you will want the user to have a way to
give values to each one. You can use the prompt() command for this. The
"prompt()" Javascript function is used to bring up a window that allows the user to type in data.
adjective=prompt("Please enter an Adjective.", "");
Take a moment to study the punctuation above. After prompt(), you need an opening (
followed by an opening ". After the quote, you put in what you want the user to see as
a description for what to put in the box. After the message, you add a closing ". Next,
you add in a comma, to show you’re moving to a new attribute, and put "" in order to
leave the next field blank. You will then need to add a closing ) followed by a ;. The
semicolon (;) is very important, as it lets the browser know to stop executing that
command. Many syntax errors arise from the lack of a semicolon.
- Finally, you should actually write the text that the user submitted in
the prompt to the webpage. This is done very simply. Again, look carefully at the
punctuation below and try to make sense out of it. "There once was a " will be written
directly to the webpage using document.write(), as we saw in the previous example.
Then, the value of the adjective variable will be written, followed by more text (" dog.")
document.write("<p>There once was a " + adjective + " dog.</p>");
Note that this is done preferably on one line. When you use the document.write() function,
you will use parentheses with quotations, much like the prompt() command. Inside the quotes, you
can put in the bulk of the story, but remember to put in spacing where it is needed.
Between each piece of text add a "+" to add (or concatenate) it together.
To call in a variable, you type the variable’s name.
- To test your script, add a closing </script> tag, save your file, and open it in your browser. As you create
your Mad Lib, be sure to save and test often.
Be creative and have fun! You should have at least 6 prompts and 5 sentences in your story.
You might want to add a link to your Mad Lib webpage off of your
main page (to allow your friends to see it).
- See a working (but very boring) example: madlib.html. Note
that you can add other stuff to the page (images, formatting, etc) just like you have
done in the past. Creativity and finishing touches (i.e., making the page look
nice) will be rewarded!
Tracking Down Errors
The most frustrating moment in JavaScript programming comes when you try to view your JavaScript-powered
page in a web browser and nothing happens. Most browsers silently ignore JavaScript errors. If you'd like to figure out
what's wrong, there are ways to track errors. Most web browsers keep track of errors and record them in a separate
window called an error console. In Firefox (on the Macs) go to Tools → Web Developer → Browser Console, and
pick the "Errors" tab. In Chrome, use the keyboard shortcut Command + Option + J (on Mac) or Control + Shift + J
(on Windows/Linux). You'll see many things here, including CSS errors in addition to JavaScript errors.
Tasks for lab
- Quickly read the Introduction and Chapter 1. You should go back and read them, in addition to
Chapter 2, carefully later.
- Complete Exercises 1, 2, and 3. In the end, you should have completed versions of
hello.html, hello2.html, and madlib.html.
- If you have time, experiment with using other JavaScript features on your own!