This is the start of the ClientCore book. ClientCore is about the technologies of the Web browser: HTML, CSS, and JavaScript. The tech in ClientCore is the most important tech for Webers.
This is a hands-on book. So, fire up your editor, have your FTP client handy, and let’s get ready to r-u-u-u-u-u-mble!
If you don’t know what an FTP client is, and you don’t have a hosting account, please read Foundations first.
The foundations book explained how browsers use HTTP to get HTML files from servers. Let’s open up those files and look inside.
By the end of this chapter, you should:
Let’s get started.
By the end of this lesson, you should know:
title right.Web pages are plain text files. Most have more-or-less the same structure. Here it is:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>TITLE</title>
</head>
<body>
BODY
</body>
</html>
Figure 1. Standard page template
Have a look at this page in your browser.
The page is made up of tags. Tags use < and >. Most tags come in pairs, like <title></title>. The first part – <title> – opens the tag. The second part – </title> – closes the tag. You’ll see this pattern a lot. Open tag, close tag, open tag, close tag.
Upload the code in Figure 1 to your server. I’ll lead you through it this time.
We’ll do the following:
On your computer, create a new directory for each exercise. For example, within your My documents directory, you might create a directory called coredogs.

This is where all of your CoreDogs work will go. Within that, make a directory called clientcore (lowercase only!). Your work on ClientCore exercises will go here. Within clientcore, make a directory for each chapter. The directory for this chapter might be called web-page-with-text. Within that, make a directory for this exercise called upload-template.
You’ll end up with:

Try to keep things organized. It’s a little more effort at the beginning, but it will save you trouble later.
Start an editor, like Notepad++. Download and install Notepad++ if you haven’t already. It’s free.
As I’m writing this, the name of the file you want is npp.5.7.Installer.exe. Download that file, and run it. It will install Notepad++.
Remember, do not use Microsoft Word, or another word processor. Use a plain text editor. Word and other word processors add extra stuff to files, and that will mess up your work.
Run Notepad++, or another editor you choose. Notepad++ will open with an empty file.
Copy the code in Figure 1. There’s an easy way to do this that doesn’t get the line numbers. Rest the mouse anywhere in the figure. A toolbar appears in the upper right corner of the figure:

The second button will copy the code in the figure to the clipboard, without any of the line numbers. W00f!

Paste the code into Notepad++. Save the file into the upload-template directory on your computer. Call the file template.html, or some such. Remember to use only lowercase letters in the file name. This is because your Web server probably runs Unix, which is case-sensitive. It thinks that template.html and Template.html are different files.
Start your FTP program, like WinSCP.
Connect to your Web server. We talked about this process earlier. Here’s a reminder.
When WinSCP starts, it will show you a Login dialog. click New, and enter your connection information from the email you got from your Web hosting company. Like this:

You’ll see a split screen, like this:

If you see just one window, with no split, you probably chose the wrong interface when installing WinSCP. To fix it, click Options | Preferences (that is, click Options on the menu bar, then Preferences – at the bottom of the menu). Choose Interface. Select the Commander interface and click OK. Restart WinSCP for the changes to take effect.
Remember that only files under your Web root will be accessible on the Web. On Hostgator, the Web root is usually called www or public_html. So that’s where your file should go.
Create a new directory on your server (under your Web root) for CoreDogs projects. You might call it coredogs. Within that, create separate directories for each chapter and project. Just as you did on your PC.
To create a directory, navigate to the parent, that is, the directory that will contain your new directory. So if I wanted to create coredogs under www with WinSCP, I’d double-click on www, and create the directory there.
In WinSCP, press F7 to create a directory, or use the button at the bottom of the window:

You’ll see a dialog that lets you type the name of the directory:

Click OK, and the new directory will appear. W00f! Double-click on the directory to open it. You can create more directories under that one.
As with the files on your own computer, I recommend creating a separate directory for each book (e.g., clientcore), and within that a directory for each chapter (e.g., web-page-with-text), and within that a directory for each exercise (e.g., upload-template). That would give you a path like /www/coredogs/clientcore/web-page-with-text/basic-template. This seems like a lot of work, but it’s better than accidentally erasing things you need.
Time to upload the file. Find the file you created (maybe you called it template.html) in the left window. Remember that the left window is the file system on your computer.
WinSCP has a drop-down that gives you quick access to your Desktop, documents, drives, and such:

Use the drop down and the directory tree below it to navigate to where you stored the file you created.

Upload a file with good old drag-and-drop, from the left to the right:

You should see your file on the server. W00f!
Wow, that’s a lot to go through to upload a file.
True. But after a while it gets to be second nature. You won’t even think about it.
Can’t you just give me a script for everything? Tell me what to click, and then I’ll click it. I don’t need to actually know all this stuff about FTP. I’ll just follow the instructions.
That would be nice, but it wouldn’t work. Trying to memorize each small step is too hard, and too inflexible.
Instead, remember the larger steps that each small step is a part of. Such as:
But I only do the little steps. You work out the list of steps, and I’ll just follow them. Why is that a problem?
Because things change.
Say that you switched from Hostgator to another company. Let’s call it Serverdile. They use SCP instead of FTP (FTP is a more secure version of FTP). Someone who just memorized the small steps would be stuck. S/he would get to “Select FTP” step, and would do the wrong thing. It wouldn’t work, and s/he wouldn’t know why.
Someone who knew what s/he was doing would know, “Oh, this affects the ‘Connect to server’ step. I’ll change that one thing.” Everything would be just fine.
Suppose you were hiring someone for a job. Who would you rather have as an employee?
The first person would need constant hand-holding. S/he would run back to you every time something changed, saying “These steps don’t work anymore. Please fix them.” Things change a lot in tech land. You would be forever fixing things for this employee.
The second person would change the instructions him- or herself. S/he wouldn’t interrupt you constantly.
Which person would be a better employee? Which one would you hire? Which one would you pay more?
If you want a job where someone tells you exactly what to do all the time, well, you might spend the rest of your life in low paying jobs. Good luck with that.
So you’ve uploaded the file, from your PC to your server. Other people can now see the file on the Web.
We talked earlier about the relationship between server files and URLs. Remember that for a static site, a URL is a path to a file on a server’s hard disk. That is, a path from your server’s Web root (like /public_html/) to the file. So if the file was at /public_html/mydir/evil.html on the server, its URL would be http://siteofdoom.com/mydir/evil.html.
Open up a browser. Type in the URL of the file you just uploaded. For example, if your site was drewid.com, you might enter http://drewid.com/coredogs/clientcore/web-page-with-text/upload-template/template.html.
You should see something like this in your browser:

W00f! W00f! W00fy-w00f-w00f! With w00f sauce!
Later, if you forget the basics of creating and uploading a page, come back to this exercise.
Enter the URL of your page as your solution to this exercise.
(Log in to enter your solution to this exercise.)
So you’ve uploaded the template. Let’s have another look at it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>TITLE</title>
</head>
<body>
BODY
</body>
</html>
Figure 1 (again). Standard page template
Tags are nested, that is, tags are inside other tags. It’s important to get the nesting right. Inner tags should be closed before outer tags.

Figure 2. Tag nesting
What happens if you violate nesting? Well, maybe nothing, maybe something. Different browsers handle invalid HTML differently. Sometimes it will look fine in Internet Explorer, but not in Firefox. Or it might look OK on a Mac, but not a PC. It’s hard to tell without looking at all the combinations.
Webers strive for predictability. They want to create a page once, then have it work on every browser, on every operating system. That isn’t always feasible. But the more closely you follow the rules of HTML, the better off you’ll be.
Use consistent indenting to make HTML easier to read, and errors in markup easier to spot. (“Markup” is just another name for text with HTML tags in it.)

Figure 3. Indenting
Browsers don’t care about indenting. Both pieces of code in Figure 3 would render identically in a browser. But the first one is easier to follow.
If it looks the same to the user, why would it matter? In the end, it’s the user experience that’s key.
Can I answer that one?
Sure.
It’s change again. The one thing you can count on is change.
A page might be fine today. But tomorrow, a marketing type is going to want to change the text. And next week, it will be different again.
The easier the markup is to read, the easier it will be to change. And the fewer mistakes you’ll make.
Webers think not only about the results (that is, the HTML page), but about the work processes they use to create the results. They try to make the work processes fast and accurate. The indenting in Figure 3 would help.
Let’s look at Figure 1 again.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>TITLE</title>
</head>
<body>
BODY
</body>
</html>
Figure 1 (again). Standard page template
The first line tells the browser what HTML standard we are using. The World Wide Web Consortium (W3C) is the organization that creates HTML standards. The current standard is HTML 4.01, though HTML 5 is waiting in the wings.
Line 1 says we’ll use the 4.01 standard, and we’ll be complying with it strictly. “strict” will give us the most predictable results across browsers.
<head> sectionAll of the HTML is between the <html> tags on lines 2 and 10. <html> is a matched pair, as are most tags.
The code inside the <html> tag has two parts: the <head> section (lines 3 – 6), and the <body> section (lines 7 – 9). The <head> section contains metadata, that is, data describing the page.
Line 4 tells the browser what character set the page will use. A character set is a list of all of the symbols that can be used for a document. For example, the ancient Egyptians wrote hieroglyphs. Wikipedia says this means “tongue:”

Figure 4. Tongue
If you listed all of the different hieroglyphs they used, you would have their character set.
At one time, computers could only store upper- and lowercase letters (A-Z and a-z), digits (0-9), and a few symbols (&, @, !, space, etc.). This was called the ASCII character set.
The ISO-8859-1 character set improved on ASCII, with characters like é and ß. Better, but still not great. What about Cyrillic and Chinese characters? Huh? Huh?
Today, character sets like UTF-8 include thousands of symbols.
The two most common character sets on Web pages are ISO-8859-1 and UTF-8. The former works for Western languages, and many Webers use it. UTF-8 is slowly taking over, however. Everything that is in ISO-8859-1 is in UTF-8. We’ll use UTF-8.
The character set definition (line 4 in Figure 1) is typical of the tags in the head section. It tells the browser about the page, but doesn’t tell the browser what to show on the page. Line 4 tells the browser that the page could contain Chinese, Cyrillic, Greek, and other characters. But it doesn’t tell the browser what characters it will show to the user.
<title>Here’s Figure 1 again.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>TITLE</title>
</head>
<body>
BODY
</body>
</html>
Figure 1 (again). Standard page template
Line 5 is the <title> tag. It doesn’t affect the main area of the page itself, but it does show up. But where? In line 5, the text for the title is TITLE. Have a look at the page template in Figure 1 in your browser. Where do you see TITLE?
Find it yet? I’ll wait.
Do do do do-do do do doo, do do do do doo, do-do-do-do-do do do do do-do do do doo, do, do-do do do, do, do, dum dum.
Yes, it’s in the top area of the browser’s window.

Figure 5. Page title
The title tells the user what the page is about.
The title appears in other places as well. First, if the user bookmarks the page, the title will show up in the bookmark list.
Second, the title will appear in search engine listings for the page. Suppose I want to know more about the musical episode of Buffy the Vampire Slayer, which, as everyone knows, is the best television ever.
I’m a Buffy fandog.
I just searched, and got this:

Figure 6. Buffy search
I went to the page, and saw this in the browser’s title area:

Figure 7. Browser title area
Then I looked at the page’s code. Here’s what it said:
<title>Once More, with Feeling (Buffy the Vampire Slayer) - Wikipedia, the free encyclopedia</title>
Figure 8. <title> tag
So the value in the <title> tag showed up in the browser title area, and the search results.
You may have seen search engines show “Untitled” for a page. This means that a Weber forgot a <title> tag.
Search engines also use the <title> tag to figure out what the page is about. If your title is “Dogs of Doom,” and a Googler searches for “doom dogs,” there’s a good chance Google will show your page. All because of the title.
The <title> tag is probably the most important tag in SEO, or search engine optimization. This is the art of getting your pages to rank high in search engine results.
While researching this lesson, I came across some interesting code. I saw the following in Google:

Figure 9. Google listing
Strange title for a page! No way to know what the page would be about, just from the title.
I looked at the code of the page, and saw this:

Figure 10. Broken title
The page starts off OK, except for the missing DOCTYPE tag. It opens a title tag at (1). But then there’s a DOCTYPE! Huh? A complete page is embedded in the title tag of a page!
The real title is at (2), but the browser can’t pick it up. The code is so messed up that the browser can’t figure it out. And neither could the Google search engine.
This shows you the importance of well-formed markup, that is, markup that follows the rules of HTML. The code in Figure 10 is not well-formed. It confuses browsers. And it won’t show up right in searches, so people are less likely to find the page. I just found it by accident.
Here’s Figure 1 again.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>TITLE</title>
</head>
<body>
BODY
</body>
</html>
Figure 1 (again). Standard page template
The actual content of the page is in the <body> section, from lines 7 to 9. This is where the real action happens.
There isn’t much there at the moment. Let’s add some stuff in the next lesson.
Say I’m looking at a Web page. Can I check out the HTML behind it?
Yes, you can. In Firefox, press Ctrl-U (Windows) or Cmd-U (Mac). Or in the menu, View | Page source:

Try it. Bring up the template page in your browser. Now look at the page source. Compare it with Figure 1.
You learned about:
title right.Let’s start adding some HTML tags to the body.
By the end of this lesson, you should know:
Some situations come up again and again. For example, a bunch of people need to make a choice. Eat all the dog food now, or save some for later? Which movie should we watch? Pirates or ninjas?

Figure 1. Pirates or ninjas?
People have come up with different ways of solving the “group makes a choice” problem. One way is for each person to vote:

Figure 2. Direct voting
This is a pattern, that is, a common way of solving a common problem. We could describe the pattern like this:
Goal: Group decision
Pattern: Direct voting
Works well: When there are a few voters.
Another pattern is to have the people elect representatives. The representatives make the choice on behalf of everyone.

Figure 3. Representative voting
The pattern is:
Goal: Group decision
Pattern: Representative voting
Works well: When there are many voters.
So direct voting and representative voting are common ways of solving a common problem. They’re useful in different situations. One is better when there are just a few voters. One is better when there are lots of voters.
There are patterns for Web sites, too. Suppose an organization called Public Opinion hires you to:
Make a Web site about the pirates versus ninjas debate. It will have four pages. The first one will be the home page, telling people what the site is for. There’ll be a page about pirates. There’ll be another page about ninjas. And the last page will let people vote.
We want everyone to know that Public Opinion owns the site. And that each page is copyrighted.
Also, make it easy for people to get from one page to another.
How do you get started? One way is to look at the goals, and think about patterns. For example, how to let everyone know that its Public Opinion’s site? One way is with a header on every page, like this:

Figure 4. Header pattern
People are used to this pattern. A lot of Web sites use it, including CoreDogs. The pattern is a solution to a common problem: tell people what a site is and who owns it.
Another goal is to tell people that each page is copyrighted. A common pattern for that is to put a copyright notice in the footer of every page:

Figure 5. Footer pattern
Again, we have a common solution to a common problem. How to show a copyright statement? Put it in the footer of every page. Lots of sites do this. Including CoreDogs.
Now, how about this goal: “make it easy for people to get from one page to another.” A common pattern is the nav bar, short for navigation bar. You’ve seen lots of these:

Figure 6. Horizontal nav bar pattern

Figure 7. Vertical nav bar pattern
Either one would work.
You’ll learn how to make all of these pieces in CoreDogs. Put the pieces together, and you have an entire design:

Figure 8. Complete page design
Patterns let you do Web work more quickly. You don’t have to relearn all of the time. You learn how to make a nav bar once, and you can use the pattern on site after site.
Patterns make it easier to design sites. You don’t have to think up new solutions to the problem of letting people jump from page to page easily. You already know that nav bars will do this. You can say to yourself, “Self, I’ll put a horizontal nav bar in here,” and leave the details for later.
Patterns make it easier for Web workers to talk to each other. Say “horizontal nav bar,” and every Web designer will know what you mean.
As we go through CoreDogs, we’ll take useful patterns, and add them to a library. When you create a page or a site, you can borrow patterns from the library.
To get to the library, click on the Tools tab, and then the Patterns tab:


Figure 9. Accessing the pattern library
Here’s your first pattern. It’s the template from the previous lesson.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>TITLE</title>
</head>
<body>
BODY
</body>
</html>
Figure 10. Standard page template (again)
Pattern: HTML page template
To make a simple Web page, begin with this pattern. Copy-and-paste the code into your editor, and get started.
Notice that this template has several different tags in it: <html>, <head>, <body>, and others. Individual HTML tags aren’t very useful by themselves. It’s when tags are combined into patterns that they start to do useful work.
You saw this just above:
Pattern: HTML page template
It tells you that a pattern for what you just read about is in the pattern library. In this case, the code in Figure 10 is in the library.
Remember: patterns are your friends.
You learned about:
title right.Let’s start adding some HTML tags to the body.
On the previous page, you uploaded a standard template for a Web page. Let’s add some tags to it.
Most documents have headings. A heading is like “Headings and paragraphs” just above. It identifies a piece of a document.
Create headings with tags <h1>, <h2>, <h3>, <h4>, <h5>, and <h6>. The tags close in the normal way, so the full tags are <h1></h1>, <h2></h2>, <h3></h3>, <h4></h4>, <h5></h5>, and <h6></h6>.
This is what they look like:

Figure 1. Heading tags
So if I’m writing an article, and I have three sections: Introduction, Evidence, and Conclusion. I would do it like this, right?
<h1>Introduction</h1>
<h2>Evidence</h2>
<h3>Conclusion</h3>
No, that’s a common mistake. The numbers in the heading tags are not the sequence of things. They’re the level in an outline.
Let’s say your article had these headings and subheadings:

You’d use HTML like this:
<h1>Introduction</h1>
<h1>Evidence</h1>
<h2>Creating the survey</h2>
<h2>Gathering data</h2>
<h2>Analyzing results</h2>
<h1>Conclusion</h1>
<h2>Humans are strange</h2>
<h2>Further research</h2>
Oh, OK, I get it. The numbers are whether it’s a heading, a subheading, a subsubheading, and so on.
Right!
So, headings separate sections of content. Most sections contain paragraphs. A paragraph is some text with white space before and after it. You’re reading a paragraph now.
Paragraphs are created with the <p></p> tag.
Here’s a page using heading and paragraph tags.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Building a Dog House</title>
</head>
<body>
<h1>Building a Dog House</h1>
<p>Building a dog house is easier if you work out what you are doing ahead of time. This page will help you with the process.</p>
<h2>Find a plan</h2>
<p>The first step is to find a plan for the dog house. There are many plans on the Web. But you need to choose carefully.</p>
<h2>Buy the materials</h2>
<p>Buy the wood, fasteners (nail, screws, etc.), paint, and whatever the plan calls for.</p>
</body>
</html>
Figure 2. Page using headings and paragraphs
You can show the page in your browser.
An <h1> is used to show the user the name of the page. This is the same as the <title> on this page, but isn’t always. For example, the page you’re reading now has <h1>Basic HTML tags</h1> for the user, but <title>Basic HTML tags | CoreDogs</title> for the browser title and search engines. This page’s title is the heading with the site name appended to it.
“Appended” means “added to the end.”
On the dog house page, <h2> is used to start the major sections of the page. You don’t have to use heading tags this way. The browser doesn’t know anything about sections and subsections. You tell it to show a heading, and it will do so. You could have HTML like this.
<h5>Building a Dog House</h5> <h1>Building a dog house is easier if you work out what you are doing ahead of time. This page will help you with the process.</h1> <h3>Find a plan</h3> <h2>The first step is to find a plan for the dog house. There are many plans on the Web. But you need to choose carefully.</h2>
Figure 3. Strange headings
The browser will do exactly what you tell it to, but it would look strange to the user.
Create a Web page using the markup in Figure 2, but change it to use the markup in Figure 3. What do you think of the result?
(Log in to enter your solution to this exercise.)
A question.
Yes?
Do you use <h1> and <p> in CoreDogs?
Yes. If you look at the source code for this page, you’ll see them.
OK. But the fonts on the dog house page look nothing like the fonts on this page. How can they be the same tags?
The HTML tags are semantic. For example, <h1> says to “make a major heading.” But the tag doesn’t say exactly how to make a major heading, that is, what fonts, colors, etc. to use. It’s up to the browser to figure out how.
From reading books and magazines, we’re used to the concept of headings. And we’re used to them being in a larger font, and maybe bold. What you see when you look at the dog house page are the browser’s defaults for making headings and paragraphs. The defaults match our expectations.
However, Webers routinely change the way HTML tags are rendered. They explicitly tell the browser what font to use for <h1>, <p>, and so on.
That’s what I did with CoreDogs. The typeface for an <h1> is Trebuchet, Helvetica, or a generic sans serif, depending on your computer (most people will see Trebuchet). The font size is 24 pixels. We’ll talk more about typefaces and font sizes later.
The technology to change the way browsers display <h1> and other tags is cascading style sheets (CSS). It’s a key Web tech. You’ll start learning about it later in this chapter.
Pattern: Headings and content
Sometimes you want a paragraph to spread over several lines, without chunks of white space. Limericks have this formatting. For example:
<h1>In honor of Jim Porter</h1> <p>Kieran wrote this for Jim's birthday.</p> <p> There once was a Porter named Jim,<br> Whose voice filled the church to the brim.<br> But his puns were so bad,<br> He was bound and gagged,<br> Until it was time for the hymn.<br> </p>
Figure 4. The <br> tag
You can see the page.
The <br> tag at the end of each line breaks the line there, and continues at the beginning of the next line. It’s different from the <p> tag, because it doesn’t add white space above and below the line.
Create a page with the markup in Figure 4. Put the markup for the limerick all on one line, like this:
<p>There once was a Porter named Jim,<br>Whose voice filled the church to the brim.<br>But his …
How does it look in a browser? Is it any different from my page?
(Log in to enter your solution to this exercise.)
There are many ways to indent content. A simple way that just uses HTML is to use the <blockquote> tag.
Here’s Jim’s code, with the limerick indented.
<h1>In honor of Jim Porter</h1> <p>Kieran wrote this for Jim's birthday.</p> <blockquote> There once was a Porter named Jim,<br> Whose voice filled the church to the brim.<br> But his puns were so bad,<br> He was bound and gagged,<br> Until it was time for the hymn.<br> </blockquote>
Figure 5. The <blockquote> tag
You can try it.
You can add simple lines with the <hr> tag. hr stands for “horizontal rule.”
Webers sometimes use them to separate parts of a page. For example, many pages have footers, giving copyright and other information. I might add the following to the limerick page:
<hr> <p>© 2010, CoreDogs.</p>
Figure 6. The <hr> tag
You can see it in action.
There’s something strange in Figure 6. What’s that © thing in line 2?
This is called an HTML entity. It’s a code for a special character of some sort. For example, © renders as ©.
HTML entities are useful things. For example, suppose you wanted to write a page about HTML. You wanted to display this:
The
<p>tag renders a paragraph.
You type the following into your HTML file:
<p>The <p> tag renders a paragraph.</p>
See the problem? The browser hits the second <p> – the one between the words “The” and “tag” – and it starts a new paragraph. Ack!
You can use HTML entities instead, like this:
<p>The <p> tag renders a paragraph.</p>
< renders as <, and > renders as >. Now the content will look right.
Another useful entity is . It’s a nonbreaking space. Normally browsers collapse spaces together. Suppose you put six spaces together in your HTML, like this:
<p>Mostly harmless</p>
The browser will display them as one space:
Mostly harmless
Use several when you want several spaces. This:
<p>Mostly harmless</p>
will show as:
Mostly harmless
Wikipedia has a list of HTML entities.
The chapter is about creating HTML pages with plain text. This lesson covered the heading, paragraph, line break, block quote, and horizontal rule tags. We also talked about HTML entities.
Let’s look at some tags you can use to do simple font work.
You know how to create a Web page with headings, paragraphs, line breaks, and other things. Let’s have a look at some simple tags for font rendering.
Note that most font work is done in CSS. We’ll look at that in the next lesson. The tags here only give you limited control.
The <strong> tag makes text grab the reader’s attention. <strong> usually makes text bold. I say “usually,” because a Weber can change this (though few do).
Here’s an example:
<p>"Sir, I am a <strong>dog</strong>, not a cat!" said the Scottie.</p>
“Sir, I am a dog, not a cat!” said the Scottie.
Sometimes I use <strong> when introducing a new term, like cascading style sheets.
The <em> tag usually makes text italic. I use <em> when something is important, or to add stress to mimic speech.
An example:
<p>"But are you <em>happy</em>?" asked the cow.</p>
<p>"Yes," replied the dog. "<em>Very</em> happy."</p>
“But are you happy?” asked the cow.
“Yes,” replied the dog. “Very happy.”
You can imagine a cow and a dog talking, with stresses on the italicized words.
Create a page that looks something like this when rendered.

When you have finished, compare the HTML source code of my solution with yours. Look at the way my HTML is laid out, especially the indenting.
Upload your solution to your server, and enter the URL below.
[solution]You can try my solution
(Log in to enter your solution to this exercise.)
In this lesson, we talked about basic font manipulation with <strong> and <em>.
These tags let you do a little basic font work. Let’s see how you can take it further, and change typefaces, colors, and other stuff.
You know what the structure of a Web page is, and how to use some simple tags to add content. But the pages you’ve created so far are, well, plain. Time to fix that.
This page is about typography, the way that text looks.
By the end of this lesson, you should:
Most people use the word “font” in an imprecise way, without understanding all the different things that go together to make up a font. That’s OK, but when you do Web work, it helps to understand the pieces.
The font of a character depends on its typeface, weight, variation, color, and other things. Let’s look at the main properties.
Typeface is what many people mean when they talk about fonts. Typeface is the basic shape of a character. The shape is modified with bolding, underlining, and other things, to create fonts.
Here are some common typefaces on a Windows PC:

Figure 1. Typefaces
One way typefaces differ is whether they are serif or sans serif. Times New Roman is a serif typeface. Let’s zoom in on a word:

Figure 2. Serif typeface
You can see that there are decorations on the characters. The decorations are called serifs.
Arial is a sans serif typeface. “Sans” means “without.” Let’s zoom in on a word:

Figure 3. Sans serif typeface
You can see that it doesn’t have those decorations.
Serif fonts can improve readability, because they give your eyes extra horizontal lines through the text. However, this only works at medium to large font sizes. At smaller sizes, the serifs can make these fonts difficult to read on a computer screen.
Many Web pages uses sans serif fonts for regular body text. Serif fonts, if used at all, are reserved for headings.
So one way typefaces differ is whether they are serif or sans serif.
Another way they differ is whether they are fixed or proportional.

Figure 4. Fixed vs. proportional
On the top line, each character takes the same amount of horizontal space. The “l” and the “o” in “love,” for example, have the same width. The typeface has serifs on the l to make it wider. This is a fixed typeface, or fixed space typeface.
On the bottom line, the “l” in “love” takes less horizontal space than the “o.” This is a proportional typeface.
Serif fonts can be proportional. Compare the widths of the “i” and the “m” in Figure 2.

Figure 2 (again). Serif typeface
There are also “cursive” and “fantasy” typefaces. Here are some examples.

Figure 5. Cursive and fantasy typefaces
You wouldn’t use them for large blocks of text. They’re for headings and other things you want to draw attention to.
The typefaces in Figure 1 are for Windows. Macs and Linux machines don’t always have the same typefaces. So if you use Windows typefaces on a Web page, the page might not look right on a Mac. We’ll see how to deal with this later.
It’s not worth being picky about the correct use of the words “font” and “typeface,” because most people don’t know or care about the difference. I use the term “font” mostly, even when I’m talking about typefaces. I only use “typeface” when I need to be precise.
There are many ways of specifying font size: points, ems, and others. We’ll use pixels; it’s the simplest thing to do. A pixel is a dot on your screen. We’ll talk more about pixels later.
I find 14 pixels to be a good base size.
Here’s some text in different sizes.
Font size: 10px.
Font size: 14px.
Font size: 18px.
Font size: 24px.
Font size: 48px.
Weight refers to how bold the font is. Most people stick to two choices: bold and normal.
There are other font variations. Some people like to use small caps for headings:

Figure 6. Small caps
Color is a complex topic. We’ll talk more about it in the chapter on images. For now, just know that there are some common color codes you can use on the Web.
You can see a color chart. Here’s a sample:

Figure 7. Color sample
Colors have names and codes. The names won’t always work, so we’ll use the codes. You could try to work out the codes yourself. But most people find a color they like on a color chart, and copy-and-paste the color code.
You’ve seen how fonts vary, with different typefaces, weight, size, color, and so on. How do you actually get those effects on the screen?
Here’s a page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>A page</title>
</head>
<body>
<h1>A page</h1>
<p>This is a page.</p>
<p>It is <strong>not</strong> a dog.</p>
<h2>This is subheading.</h2>
<p>That subheading is not a dog, either.</p>
</body>
</html>
Figure 8. A page with no styling
It looks like this is my browser:

Figure 9. Page rendered
You can see the page in your browser.
Let’s add some new stuff to the <head> of the page.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>A page</title>
<style type="text/css">
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
background-color: #F5F5DC;
}
h1 {
color: #660000;
}
h2 {
color: #006600;
}
p.important_note {
color: red;
font-weight: bold;
font-variant: small-caps;
font-style: italic;
}
</style>
</head>
<body>
<h1>A page</h1>
<p>This is a page.</p>
<p>It is <strong>not</strong> a dog.</p>
<h2>This is subheading.</h2>
<p class="important_note">That subheading is not a dog, either.</p>
</body>
</html>
Figure 10. Styled page
It looks like this:

Figure 11. Styled page rendered
You can see the page in your browser.
Lines 6 to 24 tell the browser that I want to change the way the page looks. The technology for this is called CSS, for cascading style sheets. Lines 7 to 23 are called a style sheet.
A style sheet uses rules. The syntax of the rules is not the same as HTML tags. The official standards for CSS are separate from the official standards for HTML.
Here’s the first rule:
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
background-color: #F5F5DC;
}
This part:
body {
is a selector. It tells the browser what the rule applies to.
This rule applies to the <body> tag, which includes all of the content of the page. The <body> is the container of the page’s <h1>, <h2>, and <p> tags. Rules applied to containers apply to their contents as well.
font-family changes the typeface:
font-family: Arial, Helvetica, sans-serif;
Recall that different computers have different typefaces installed. Arial is a standard Windows typeface. But what if the user has a Linux machine? There’s a good chance that the computer won’t have Arial.
In that case, the browser goes down the list, and chooses the first typeface that is installed on the machine. So, the browser will look for Arial first. If that isn’t on the computer, the browser will look for Helvetica. That’s a standard Mac typeface. If the browser can’t find that either, it will look for sans-serif. This isn’t an actual typeface, but instead tells the browser “use the system’s default sans serif typeface, whatever it is.”
If a typeface name contains spaces, you need to put quotes around it, like this:
font-family: "Trebuchet MS", Helvetica, sans-serif;
Here’s that rule again:
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
background-color: #F5F5DC;
}
We’ve talked about the first bit, the font-family.
The next style is:
font-size: 14px;
This sets the page’s default font size to 14 pixels. Some tags will adjust this. <h1> will choose something bigger, for example.
The last style in the body rule is:
background-color: #F5F5DC;
This sets the background color on the page. Where did that strange code come from, the #F5F5DC? I started by looking at the color chart. I found a color I wanted – beige – and wrote down its color code. Then I used the code as the background-color.
Let’s look at the stylesheet again:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>A page</title>
<style type="text/css">
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
background-color: #F5F5DC;
}
h1 {
color: #660000;
}
h2 {
color: #006600;
}
p.important_note {
color: red;
font-weight: bold;
font-variant: small-caps;
font-style: italic;
}
</style>
</head>
<body>
<h1>A page</h1>
<p>This is a page.</p>
<p>It is <strong>not</strong> a dog.</p>
<h2>This is subheading.</h2>
<p class="important_note">That subheading is not a dog, either.</p>
</body>
</html>
Figure 10 (again). Styled page
We covered the body rule in lines 7 to 11. It was a long discussion, because everything was new.
The next rule is:
h1 {
color: #660000;
}
The rule applies to all <h1> tags on the page. It leaves everything alone (typeface, weight, etc.), except for the color. 660000 is a dark red that I like for headers, so I used it here.
The next rule is:
h2 {
color: #006600;
}
Like the previous one, it just changes a tag’s color, this time to a dark green. All of the <h2>s on the page will be dark green.
The last rule is a little different. Sometimes you want to give text on a page a special look. For example, you might want all <p> text to look the same, except when you want to draw the user’s attention to something special. Maybe you want text like “On sale! Today only!” to stand out.
Here’s the rule:
p.important_note {
color: red;
font-weight: bold;
font-variant: small-caps;
font-style: italic;
}
The period (.) after the p creates a CSS class. A class is a rule that I can apply selectively. I can use it on some <p>s, and not others.
The class is named important_note. I made up that name. I could have called it read_me_now, or something else.
Now I have two styles for <p> tags: the regular style, and the important_note note style. I choose when I want to use one with the class attribute of the <p> tag. For instance:
<p>It is <strong>not</strong> a dog.</p>
<p class="important_note">That subheading is not a dog, either.</p>
The first paragraph uses the regular style. The second applies the important_note class.
You can also define classes like this:
.important_note {
color: red;
font-weight: bold;
font-variant: small-caps;
font-style: italic;
}
The p is gone from the selector. You can apply this class to any tag. E.g.:
<h2 class="important_note">Warning! Cat detected!</h2>
All of the style rules are inside these lines:
<style type="text/css">
...
</style>
Do I have the include those?
Yes. <style> is an HTML tag. It tells the browser that you’re going to be adding some style rules. Don’t forget the <style> tag.
Make a page that looks like this:

Hints:
<h1> and <p> in the <body>.attribution for the last line.Upload your solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
Several different CSS properties set font types. Sometimes you use font-style:
font-style: italic;
No prizes for guessing what that does.
Sometimes you use font-variant:
font-variant: small-caps;
Lowercase characters use the shape of uppercase characters, but at a smaller size. An interesting effect.
Sometimes you use font-weight:
font-weight: bold;
I wonder what that does? Hmm… You can also use
bolderandlighter.
Sometimes you use text-decoration:
text-decoration: line-through;
Puts a
line through the text.
When I want to, say, put a line through some text, I often forget whether I need to use text-decoration, font-variant, or something else. I look it up. A good place to start is the SitePoint reference.
Left alignment
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Right alignment
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Center alignment
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
There’s only one property here:
text-align: left;
... or right or center. That’s it. For example:
h1 {
text-align: center;
}
... would center all <h1>s.
Here’s another example:
p.aside {
text-align: right;
}
This creates a class called aside. Use it like this:
<p class="aside">Dogs are cool!</p>
Here’s how it renders:
Dogs are cool!
Make a Web page that’s a template for company reports. Here’s a screenshot (made narrow to fit):

Figure 1. Report template
The typeface is Verdana. The color for the background is #FFFFCC. The heading colors are #660000 and #006600. The font is 14px high.
Upload your solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
We’ve looked at the many different ways you can control typography. They affect how readable the text is.
But there are aesthetic aspects to fonts as well. Aesthetics is about the moods that fonts evoke. At least that’s how I’ll use the term.
Match the mood of a font to the text. Here are some headings for pages advertising different events.

Figure 12. Font moods
You can see which fonts match which events.
In this lesson, you learned about fonts, and how to style them with CSS. You learned to use classes to apply different styles to different page elements.
There are a lot of options with CSS. You can do almost anything!
I’m feeling overwhelmed here.
Me, too. There are so many choices!
I hear you.
Some people get into typography in a big way. But most have some simple rules that work most of the time.
Here are some things that I often do.
Pattern: Basic text styling
I vary these rules depending on the site. For instance, I might switch to serif headings, if that matches the mood of the site.
You might find some colors, typefaces, etc., you like. Keep a note of them. When you start a new project, you’ll have something good to start with.
This lesson gave you some useful guidelines. Hmm. Maybe we should remember them.
You’ve learned about paragraphs, headings, horizontal rules, CSS, and other stuff. You’ve seen some basic guidelines that I use when I format a new page.
Let’s talk a little more about patterns.
In the previous lesson, I showed you some rules that I often use for formatting text. Like “Use a 14px font for most text,” and “Use larger fonts for headings.” was that helpful?
Yes, very.
Why?
There are lots of CSS rules. You can use them in a bazillion different combinations. It was making my brain hurt.
You gave us a…, well, some CSS rules that work OK.
Where did I get those rules?
You said that you’d used them in the past, that they worked for you.
Right!
Remember that a pattern is a way of solving a problem that someone has found useful. Instead of working out the solution to a problem all over again, sometimes you can just grab a pattern than works.
CoreDogs has a pattern library. To get to it, click on the Tools tab, and then the Patterns tab:


Figure 1. Accessing the pattern library
Look at the Basic text styling pattern. It uses the guidelines from the previous lesson. The pattern includes helpful tips, like using quotes around typefaces that have spaces in their names.
Also look at the Title – Details pattern. It tells you how to use section headings. The pattern uses CSS margins. We haven’t covered that yet; that comes later. But you should be able to follow the pattern.
Some patterns are often used together, or are alternatives to each other. Both of the patterns just mentioned link to each other in Related patterns.

Figure 2. Related patterns
Patterns are shortcuts, right?
Yes.
But is using someone else’s shortcut always a good idea? It might not do exactly what you want.
Good point!
You usually need to adjust patterns, so they make sense for your use case (that is, the site you are working on at the moment). For example, the Title – Details pattern uses the same color for text and titles.

Figure 3. Title text and detail text are the same color
But maybe you want different colors.
Say you’re making a site for a school that has the color scheme blue and white. These colors are part of its branding (we talked about branding earlier). You might want the text to look like this:

Figure 4. New colors
So you need to adjust the pattern.
What this means is that you can’t just throw the pattern in without understanding it. You need to understand it, so you can change it to fit the job.
Patterns are not like Lego bricks that you can snap together. They’re more like cookie cutters.

Figure 5. A cookie cutter
Image from WikiHow.
You can just stamp out the basic shape. But if you need to, you change the shape before you put the cookie into the oven. Maybe trim off the edges of the hat, and round out the head.
Figure 6. Original and changed cookie
Adjust patterns as you need to, to fit the goals of your project.
The CoreDogs pattern library was created to help you learn Web tech. The patterns are basic, and easy to use.
Professional Webers might prefer other libraries. The Yahoo pattern library is an example.
Let’s see how you make lists of stuff.
You know the structure of an HTML page. You know about headings, paragraphs, indenting, emphasis, and other stuff. You know some basic CSS styling.
Let’s look at HTML tags that make lists. There are two types of lists: unordered and ordered.
Unordered lists look like this:
They’re called “unordered” because they just show bullets in front of each item, rather than numbers.
The list above can be made like this:
<ul> <li>An item</li> <li>Another item</li> <li>Yet another item</li> </ul>
Figure 1. An unordered list
Pattern: Lists
Notice that the <li> tags are nested inside the <ul> tags. It’s important to get the nesting right.
Also notice the indenting. The visual layout of the code matches the nesting of the HTML tags. The indenting makes the page easier to change. If you need to add things in the middle of the list, for example, the indenting will help you figure out exactly where your new data needs to go.
Find a list of dog breeds on the Web. Create a Web page with a list of five of your favorites. List them alphabetically.
Upload your page to your server, and add a link below.
(Log in to enter your solution to this exercise.)
The code for an ordered list is very similar. Change the <ul> to an <ol>, and you’ve got it.
<ol> <li>An item</li> <li>Another item</li> <li>Yet another item</li> </ol>
Figure 2. An ordered list
Pattern: Lists
This looks like:
Find a list of dog breeds on the Web. Create a Web page with a list of five of your favorites. List them in your order of preference: favorite first, next favorite second, etc.
Upload your page to your server, and add a link below.
(Log in to enter your solution to this exercise.)
Lists can be nested, that is, one list can be entirely inside another list. Here’s some code.
<ul>
<li>19th century
<ul>
<li>1836: Eunice (mastiff) crowned Bitch of New South Wales.</li>
<li>1840:
<ol>
<li>Isaac (lab) eats 15 pounds of figs at Moreton Bay.</li>
<li>Thark (sheltie) barks for 17 hours nonstop. Riots in Port Jackson.</li>
</ol>
</li>
<li>1895: Booblo (Welsh terrier) marks Barton as future PM.</li>
</ul>
</li>
<li>20th century
<ul>
<li>1915: Groft (border collie) rescues sausages under fire.</li>
<li>1967: Lilabeth (portuguese water dog) directs shark to prime ministerial snack.</li>
<li>1975:
<ol>
<li>Goofer (collie) bites PM.</li>
<li>Goofer (collie) bites PM again.</li>
<li>Kerr (govenor general) bites PM.</li>
<li>Goofer (collie) becomes PM.</li>
</ul>
</li>
</ul>
Figure 3. Nested lists
Here’s how it renders:
Figure 4. Rendered nested lists
Notice that:
<li> tags of outer lists.You can style lists with CSS. You can apply all of the font styles we looked at earlier: font-family, color, and so on.
Make a page like this:

The background color of the page is #FFFFEE. The silly text is #FF1493. The silly typeface is Comic Sans MS. The rest of the page is Arial. The base text size for the body is 14 pixels.
Hint: create two different classes for the <ul> tag, plus a rule for the <body> tag.
Upload your page to your server, and add a link below.
(Log in to enter your solution to this exercise.)
You can change the bullets in unordered lists. The “bullets” are the symbols on the left of each list item. Change them with list-style-type, like this:
list-style-type: circle;
You can use disc, circle, square, or none.
Here’s some code. You can see it in action.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Styling lists</title>
<style type="text/css">
li {
list-style-type: square;
}
</style>
</head>
<body>
<h1>Styling lists</h1>
<ul>
<li>Affenpinscher</li>
<li>Afghan hound</li>
<li>Airedale terrier</li>
<li>Akita</li>
</ul>
</body>
</html>
Figure 5. Styling list items
Make a page like this:

The bullet in the silly list is different.
Upload your page to your server, and add a link below.
(Log in to enter your solution to this exercise.)
SitePoint has a nice CSS list reference page, if you want to know more about styling lists.
In this lesson, you learned:
You know how to make Web pages with text. You know how to make them look good, with colors, fonts, and other things.
But what about the words themselves? The next lesson is about writing for the Web.
You know how to make Web pages with text. You know how to make them look good, with colors, fonts, and other things.
But what about the words themselves? That’s what this lesson is about.
By the end of this lesson, you should:
Much of the information on a Web site is in text. Some is in images; we’ll talk about that later. But getting the text right is important.
Most of the ideas on this page come from two excellent books:
(Click to buy from Amazon.com.)
(Click to buy from Amazon.com.)
You’re writing for two stakeholders:
Most users don’t “surf.” They spend time on a site because it helps them. Find a product, learn about a band, laugh at fails.
Owners spend money on a site because they have information they want users to see. Stuff on sale, tips on playing a game, when the book club meets.
The interests of users and owners may conflict. Say there’s a page about an MP3 player. Some users want just the basic facts about the product. Some owners want users to read a thousand words on why this is the best MP3 player ever.
On the Web, users are in control. If they don’t want to read a thousand words? They go to another Web site.
Site owners are not in control of user’s time. Someone will keep reading a Web page only if s/he keeps getting value from doing that.
Part of the writer’s job is to write for users, while still conveying the owners’ key messages.
Here are some guidelines for writing Web text.
Drop as many words as you can. Use simple words. Write “use simple words,” not “Avoid unnecessary linguistic complexity in the presentation of textual information.”
Keep sentences and paragraphs short.
Sentences have subjects and objects. Here’s a sentence:
The dog liked the bone.
The dog is the subject, the thing the sentence is about. The bone is the object.
Active voice means the subject comes first in the sentence, as in “The dog liked the bone.” Passive voice puts the object first:
The bone was liked by the dog.
Here’s another sentence pair:
Head bangers like this product.
This product is liked by head bangers.
You can use passive voice sometimes, but not a whole page of it. It’s harder to read, because your brain has to do more work to figure out what a passive voice sentence means.
Here’s some happy talk:
Welcome! And best wishes from everyone at X Corp.! We’re glad you’re here at our site. Thank you for coming. We value you, and just want the opportunity to make your life better, with our fine line of products. They’re great! And if you use them, you’ll be great, too! Everyone will like you. We’ll like you, and be your best friend forever. You’re in for a great experience on our site. Have a nice time!
It doesn’t help the user much.
Here’s the happy talk from the CoreDogs home page:

Figure 1. CoreDogs home page happy talk
This is the only thing on the page that isn’t about CoreDogs. I could get rid of it, but that dog is very cute.
Here’s the search field on this page:

Figure 2. Search form
You know how to use this. No instructions needed.
The tree menus:

Figure 3. Tree menus
You already know what the + and – do.
Search and the tree menu don’t need instructions because you’ve seen them before. When there’s something different on your site, you might need to add instructions.
But don’t push instructions on the user. Let the user decide whether to see them. Here’s a widget you’ve seen on the exercise pages:

Figure 4. Public widget
To get help, click on the help dog – but you decide whether you want it.
CoreDogs has a help section section. It isn’t forced on you. You decide whether you want to use it.
Write so users can quickly look over the page, without having to read it all.
Make lists look like lists, rather than putting them in text.
Here is a list:
There is the blue thing. And then the red thing. The red thing is way cool! Really, it is. Third, there’s the brown thing. Last, but not least, the green thing.
Do this instead:
Use it. People like it better.
Make the text color easy to read on the background color.
Older people have trouble with small font sizes. I use 14px as a rule. Larger for headings, of course.
Jakob Nielsen has a well-regarded piece on writing for the Web.
Julie Meloni wrote a short article on writing for the Web. It’s based on Nielsen’s work.
You are writing for site users and owners, but the users come first.
Guidelines for Web writing:
Time to work on your eMe site.
You’ve learned some text tags, and a little about styling. You know how to make lists. You’ve read about writing for the Web.
Earlier, you thought about stuff you would put on your Web site. Time to make some pages. Create at least two.
If you can’t think of anything, write some pages about yourself. One about your history. Where you were born, schools you went to, like that. The second page could be about your interests. Hobbies, music you like, games you like, etc.
Create a few more pages, if you want. Go over your list of interesting stuff.
All the pages should use the same style rules. Pick a typeface you like, colors, and so on. You can start with the basic text styling pattern, or start from scratch. Mess around, and find something you like.
Say you make four pages. They all have the same styles. One way to do this is to get the style right on one page, then copy-and-paste the <style> section into the other pages.
The problem is this: what if you decide to change the styles? Suppose you set the background color of all the pages to #FFFFC0, a brightish yellow. Then you decide you like #FFFFEE better. It’s a very pale yellow. You would have to open every HTML file, and make the same change. It would be easy to make a mistake.
You’ll learn more about color codes later.
There’s a better way:
For example, suppose I had this page. Here is the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>A page</title>
<style type="text/css">
body {
background-color: black;
font-family: Arial, Helvetica, sans-serif;
font-size: 16px;
color: #FEFEF2;
}
h1 {
color: #FFD700;
}
</style>
</head>
<body>
<h1>A page</h1>
<p>This is a page.</p>
</body>
</html>
Figure 1. A page
The first thing I do is remove all the CSS rules, and put them in a separate file. I’ll call the file styles.css, though I could call it whatever I like. Usually I give the file a .css extension, though I don’t have to. I’ll put the file in the same directory as the page.
I could put it in another directory. We’ll see that later.
Here is styles.css:
body {
background-color: black;
font-family: Arial, Helvetica, sans-serif;
font-size: 16px;
color: #FEFEF2;
}
h1 {
color: #FFD700;
}
Figure 2. styles.css
Notice that the <style> tag isn’t there. It’s HTML, and does not belong in the file.
Now, I delete the <style> section from page.html, and replace it with this:
<link rel="stylesheet" type="text/css" href="styles.css">
I put the name of the file I just created in the href attribute. Don’t forget the extension.
Here’s what the HTML file looks like now.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>A page</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1>A page</h1>
<p>This is a page.</p>
</body>
</html>
Figure 3. HTML file with external style sheet
The page will look the same as before. Have a look.
I can use this line in as many files as I like:
<link rel="stylesheet" type="text/css" href="styles.css">
I could have a hundred pages using the styles, if I want.
The <body>’s background color is black. You can see that in line 2 of styles.css:
background-color: black;
Suppose I want the background on all pages to be dark gray. I change this one line in styles.css:
background-color: #404040;
Every file that links to styles.css will change. If that’s 100 pages, then 100 pages change. W00f!
Write some pages about something on your interesting stuff list. Create at least two, but more if you like.
Make sure all the pages use the same style rules. Use an external style sheet. You can put all the files in the same directory.
Upload your files to your server. Put the URLs of the files below.
(Log in to enter your solution to this exercise.)
Time for some more exercises.
You should do the four recommended exercises. Do the optional exercises if you want more practice.
Exercises in the Explore section are more challenging. You may need to use HTML and CSS we haven’t covered yet. Get ready to Google!
Create a page that looks like this, using CSS styles:

Upload your solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
Create a page that looks like this, using CSS styles:

Upload your solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
Create a page that looks like this, using CSS styles:

Upload your solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
Create a page that looks like this, using CSS styles:

Upload your solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
Create a page that looks like this:

Match the colors approximately. Use any sans serif font. Use at least one CSS class (I used more in my solution).
I made my browser narrow to make the screenshot above, so I could fit it in this page. You don’t need to have this width.
Upload your solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
These challenging exercises may use HTML and CSS that you haven’t seen yet. Get ready to Google!
Make a page that looks like this:

Upload your solution to your server. Enter the URL below.
(Log in to enter your solution to this exercise.)
Make a page like this:

Do not use a graphics program! Use HTML and CSS only.
Upload your solution to your server. Enter the URL below.
(Log in to enter your solution to this exercise.)
Make a page like this:

Type the text into your HTML in the normal way! Copy-and-paste this into your solution:
Hey!
This is reversed!
Flip it around, willya, buddy?
Upload your solution to your server. Enter the URL below.
(Log in to enter your solution to this exercise.)
Make a page showing the YouTube video, “Potter Puppet Pals: The Mysterious Ticking Noise.” Your page should look like this:

Upload your solution to your server. Enter the URL below.
(Log in to enter your solution to this exercise.)
You know how to create basic HTML pages. The tags you’ve learned are at the heart of Web work.
In this chapter, you’ll start learning about interactivity. This means that users can click on things, drag things, type into things.
A good example is the lesson tree. You know what happens when you click on a +. This isn’t just a frill; it’s useful. You can drill down into the books and chapters, without having to look at everything.
Some effects are there just because. Like the way the tabs at the top of the page jump. I’m a geek, and proud of it!
Most interactivity is done with JavaScript. Writing interactive JavaScript used to be hard work. It’s gotten a lot easier over the past few years. Now beginners can add cool effects to their pages, make slideshows, write games, and other stuff.
Before we get too fancy, you need to learn a few basics. That’s what this chapter is about.
This chapter is about programming.
Are you crazy? I can barely balance my check book! I hate all that math stuff!
Hey, calm down. Breathe, that’s it.
Many people think they can’t do it. But my 20 years of experience says you can learn programming, at least to the level that CoreDogs covers. Which, as programming goes, isn’t a lot.
Some things to remember.
First, how you learn matters. If I threw a bunch o’ tech at you all at once, of course you’d be confused. That’s natural.
Unfortunately, most tech experts don’t have strong teaching skills. They move too fast, cover too much, too quickly. Deep down, some experts think that programming isn’t hard, so learners shouldn’t need help.
They’re wrong. Programming is hard to learn, if you try to learn it from an unskilled teacher, or a poorly written book. Most people can do it. But teachers and authors need to understand how people learn, and respect learners’ experiences.
Let’s take it slowly. In fact, really slowly for someone as anxious as you are, CC. Baby steps.
This chapter is long. The reason? We go slowly. Baby step, baby step, baby step. That might bug you if you already know how to program. Please remember that others are learning this for the first time.
Second, find someone else to learn with. Not an expert, but someone who’s at your level, or a little ahead. If you and your buddy do need expert help, pick someone who is patient.
Third, I want to kill a myth. Programming is not about math. All those sines and cosines you learned to fear? You won’t see them here. No calculus, no factoring, no quadratics.
Really? Promise?
Yes, I promise. Pinkie swear. The most complicated thing is finding the area of a circle, and I’ll even give you the formula.
Tell me something, and be honest. Could you balance your checkbook, if you really wanted to?
Well, yes, you got me, I could. I can add and subtract. Even multiply and divide, on a good day.
Then you’re all set.
The most difficult thing about programming is breaking down a large problem into smaller ones, so you can work on each small one independently. This has nothing to do with math. People who write history books do the same thing. They take big events (e.g., the American Civil War), break them into parts (e.g., The US before the war, The first shot, The south’s initial success, ...), and write a chapter for each one.
You’ve spent a lot of time on CC’s anxiety.
Yes. You might not feel it, but she does, and it will get in the way of her learning. Learning is the goal, so anything that interferes should be dealt with.
Please be patient. The three of us are a team, going through CoreDogs together. Let’s respect each other’s struggles.
By the end of this chapter, you should:
Let’s get started.
Come on CC, you can do it, girl.
Yes, you can. And I’ll hold your paw all the way.
A program is a set of instructions you give to a computer. Do this, do that, then go back and do this again.
When the computer follows the instructions, we call that running the program. Each time you run a program, the computer starts following the instructions again.
Humans run programs as well. They don’t call them “programs,” they call them “recipes,” or “directions,” or “manuals.”
For example, a human gets up in the morning, and makes some coffee. Here is the program the human follows:
When you make an interactive Web page, you give your Web browser (Firefox, IE, etc.) instructions. So the browser is the thing running your programs.
You can compare the way humans follow instructions and the way browsers run programs.

Figure 1. Humans and browsers run programs
The instructions you give the human have to be in a language s/he knows. If the human doesn’t speak English, instructions written in English aren’t much use.
What is English? English is a bunch of words, like “dog” and “camel,” and rules for using them together. “I is barking” is not valid English. “I am barking” is.
Browsers speak JavaScript. They know how to follow instructions in that language. The language has words, like “if” and “return,” and rules for using them together. tip = meal_cost * 0.15; is valid JavaScript. tip - = flargle is poot is not valid JavaScript.
Another example. Suppose you run a grocery store. You hire a human, let’s call her Xena, to help you. You write instructions for Xena, telling her what to do when someone wants to buy something, like cookies or a pencil.
The instructions are simple. The only thing Xena has to decide is whether to charge sales tax. If the item is food, there is no sales tax. If the item is not food, Xena should add 5% sales tax to the price. That’s all the instructions.
So if cookies are $2.00, Xena would charge $2.00. No tax, because the cookies are food. But pencils are not food (for humans, anyway). So if a pencil costs $1.00, Xena would charge $1.00 + $1.00 × 5% = $1.05. You get the same answer this way: $1.00 × 1.05 = $1.05. A little less work.
Here are the instructions you give Xena:
Find the item's price. If the item is food: Add 5% to the price Tell the customer the total
Figure 2. Xena’s program
Line 2 is a condition. It says to do line 3 only if the item is food.
OK, let’s see how a browser does it. Try this. Type in a price like 1 or 2 (don’t type the $), check the food box or not, and click the Compute total button.
Price
Please pay $.
Now I’m going to show you the JavaScript program. Actually, I’ll put Xena’s program and the JavaScript program together, so you can compare them.
Find the price.
If the item is food:
Add 5% to the price
Tell the customer the total
//Get the item's price from the text box.
price = $("#price").val();
//Is it food?
if ( ! $('#food').is(':checked') ) {
//No, add the sales tax.
price = price * 1.05;
}
//Output the total.
$("#pay").text(price);
Figure 3. Comparing programs
The details of the JavaScript aren’t important. You’ll learn that later. For now, just notice how similar Xena’s instructions and the computer’s program are.
BTW, the lines that start with // are comments. They’re ignored by the computer. People type them in to explain how programs work.
JavaScript programs work with the HTML and CSS on the page. The price input field, the food check box, the button, and the output are all created by HTML tags. Here’s what I used to create the price input field.
<p> Price<br> <input type="text" size="4" id="price"> </p>
Figure 4. HTML for the price input field
You learned about the <p> and <br> tags in the last lesson. The <input> tag creates the input field. You’ll learn about that later.
Most JavaScript programs work by changing HTML elements in some way. Before you write the JavaScript, you add the HTML elements you want to work with.
The program gives strange results. Like for a price of 2 for a non-food item, it tells me the price is 2.1, not 2.10.
Try typing in a negative price.
That doesn’t make sense.
Exactly. Shouldn’t the computer know that?
Good points!
Computers are incredibly stupid. They do exactly what you tell them to, even if it doesn’t make sense. I would need to add error checking if I wanted the program to do that. But I wanted to keep it simple for now.
How would you do the error checking? I’m just curious.
Part of it would be like this:
if ( price < 0 ) {
alert("Sorry, prices cannot be negative.");
return;
}
The return statement would stop the rest of the program from running.
When you write a program, you ask yourself, “If I was a Web browser, how would I do this task?” You’ll learn the language the Web browser speaks, and write instructions in that language.
So when you write a program, you pretend you’re a Web browser?
Yes, more or less. You pretend you can only understand the instructions a browser can understand, and put together a sequence of instructions to do the task.
It’s like writing a play. You imagine the actors saying the lines you write, and what effect that has on the audience. Want a laugh from the audience? Write a joke into the script.
Or giving directions to someone, how to get from the highway to your house. You imagine the route. Then you give someone instructions that will help them follow that route. “Take exit 89, turn left, go about a mile until you see Bert’s Donut Shop, turn right, ...”
So you have to know what instructions they can follow.
Right. You could say, “Drive 4,923 feet,” but people would have trouble following that instruction. Better to say, “go about a mile until you see Bert’s Donut Shop.”
Huh. That makes sense.
Think you’ll be able to write a program?
I don’t know yet.
Fair enough. We’ll see.
You’ve learned that a JavaScript program is a set of instructions that a browser follows. But what tells the browser to start following the instructions?
Think about the human programs.
An event is something that starts a program running. Events for people are waking up, someone wanting to buy something, someone wanting to visit you, etc. There are lots of events. The phone rings (you bark), someone comes to the door (you bark), you’re hungry (you bark), you’re tired (you sleep), and so on.
Web browsers have events, too. Things that happen. Like the user clicks the Compute total button. Or types something.
On the page you’re looking at now, click a + sign in the lesson tree is an event that runs some code. Another event is moving the mouse over the dog logo in the top left of the page (try it).
An event is said to trigger a program. When you attach a program to an event, you’re binding the program to the event.
In the next lesson, let’s see how you can include JS code on a Web page.
In this lesson, you’ll learn how to:
In the previous lesson, you learned that your Web browser runs JavaScript code. That is, your browser does what the JavaScript instructions say.
Your browser needs to get the programs from somewhere. It gets programs in two ways:
Let’s talk about each option.
The easiest way to add JS code is to put it directly into a page, like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Welcome</title>
<script type="text/javascript">
alert('Your dog loves you.');
</script>
</head>
<body>
<h1>Welcome</h1>
<p>Welcome to the Web site of truth and beauty.</p>
</body>
</html>
Figure 1. On-page JS
Pattern: HTML page template
You can try the page.
There’s one line of JavaScript, in line 7. The alert statement shows a message to the user.
What about lines 6 and 8? They look like HTML, with the < and >.
You’re right, they are HTML. The <script> tag tells the browser that it’s about the get some program code. If you put code on a page, you must use the <script> tag.
What about type="text/javascript"? Does that need to be there?
Yes, always include it. Some browsers can understand more than one programming language. The type attribute tells the browser what language to expect.
Your program will usually still work if you omit the type, but put it in anyway, so there is never any confusion.
In Figure 1, I put the script into the <head>. It doesn’t have to go into the <head>, but it’s common.
When I tried the page in Figure 1, the message box showed before any content. Like this:

Only after I clicked the OK button, did any content show.

Is that normal?
Yes, that’s what the browser should do. The alert() was in the HTML file (Figure 1) before any content. So it ran before any of the content showed.
This isn’t usually what we want, as we’ll see later.
What if you want to include the same JS code on many pages? You can put the code into an external file, and then tell each page to load it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Welcome</title>
<script type="text/javascript" src="alert.js"></script>
</head>
<body>
<h1>Welcome</h1>
<p>Welcome to the Web site of truth and beauty.</p>
</body>
</html>
Figure 2. Including a JS file
Pattern: HTML page template
Line 6 loads an external file. Here’s the content of the file alert.js.
alert('Your dog loves you.');
Figure 3. The JS file
If you need to change the code – maybe show a different message – then you change the one file alert.js. Every page that includes the file will be changed.
This pattern – putting stuff in a separate file and loading that file into many different pages – is used a lot. It significantly reduces the cost of changing a site.
Change the alert() message to “Be kind to your dog.” Upload your solution to your server, and paste the URL below.
(Log in to enter your solution to this exercise.)
Add a second alert() message, like “Play with your dog.” Upload your solution to your server, and paste the URL below.
Hint: Copy-and-paste the alert(...); line.
(Log in to enter your solution to this exercise.)
JS can be a pain to write. To make it easier, we’re going to use the way cool jQuery library.
Add this to your pages that use JavaScript:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
Figure 4. Including jQuery
Pattern: HTML page template
This will download jQuery from one of Google’s servers. This line downloads version 1.3.2. You can include a newer version, if you prefer.
One of the real pains of JS was that you would have to write different versions of your code for different browsers. What would work in Firefox, Chrome, and Safari would not work in Internet Explorer.
jQuery makes that problem go away. Write your code once, and jQuery will make it run everywhere. It also does animations and other cool things.
Let’s see how you write simple programs.
You know how to put JavaScript on a page, and show some messages. To go any further, you’ll need to know about variables.
By the end of this lesson, you should know:
First thing – the word “variable” in computing does not mean the same thing it does in math.
Some people think you need to know a lot of math to write programs. They’re wrong. Wrong, wrong, WRONG! Many professional programmers don’t even know how to spell “calculus,” let alone do it.
A variable is a container. It’s a piece of computer memory that you put data into.
Variables have names, like total or last_name, so the computer can tell them apart. Here are two variables in memory:
| total | last_name |
|---|---|
| 21 | Smith |
Variables can contain numbers or text.
OK, a variable is a little box with information in it. Right?
Yes, that’s a good way to think of it.
So… why would I care?
Using variables makes writing JavaScript easier. But it’s better to show you. Let’s look at how you use variables.
Sometimes you use variables to hold data you have now, that you’ll need later.
Like cake tins. Suppose you have two pies and a cake.

You eat the two pies, and a slice of cake – yum! But now you’re full.
What do you do with the rest of the cake? Throw it away?
Are you crazy? Throw away cake? No! No! No! (Shakes paw)
I’d keep the cake. I’m going to want it later. Ahhh… cake!
Where do you put the cake?
Somewhere I can find it later, when I’m hungry.
You put the rest of the cake in a cake tin.

When you’re hungry again, you the cake out of the container, and nom, nom, nom.
A variable is like the cake tin. It’s a place for storing data. You put data into the variable, and take it out later, when you’re ready to use it.
Let’s write some code that uses variables in this way. You go to the store and buy some chew toys. Specifically, the new brain chew toy:

How much do you pay for the brains? It depends on (1) how many brains you buy, and (2) how much each one costs. Multiply the two together, and that’s the total you pay.
total = number of brains x price per brain
So if you buy 5 brains, and they’re $4 each, you pay $20.
Click the button, and you’ll run a program that makes the calculation.
When you click the button, the browser asks you for the number of toys you want to buy. You type that in, and click OK. Let’s say you type 5:

Figure 1. How many toys?
The browser can’t use that 5 right away. It needs another piece of information – the price – before it can use the 5 to compute the total. We want to keep the 5 for later.
How? We tell the browser to store the 5 in a variable. When we’re ready to compute the total, the browser can get the 5 – or whatever you typed – from the variable.
Here’s the code:
var number, price, total;
number = prompt('How many brain chew toys?');
price = prompt('Price each?');
total = number * price;
alert('Total: $' + total);
Figure 2. Some code
Line 1 creates three variables, that is, three containers in the computer’s memory. Line 2 makes an input box:

Figure 1 (again). How many toys?
Whatever the user types gets put into the variable number, for later use.
Line 3…
price = prompt('Price each?');
...shows another input box. It stores what the user enters in the variable price.
Line 4…
total = number * price;
...gets the contents of number, and the contents of price. It multiplies them together (* means multiply), and puts the result into another variable, total.
Some geeks call * “splat.”
Line 5…
alert('Total: $' + total);
...gets the contents of total, and shows it in an output box.
Let’s see that again, but this time we’ll see the values of the variables as they change. They start off empty.
| number | price | total |
|---|---|---|
Try a few different calculations.
So, we know that a variable is a container for data. One use for a variable is to save data for later, until it is ready to use. In the example we just saw, the program took the number of brains the user entered, and stored it in the variable number, until the program was ready to use that data to work out the total cost.
Joe loves to play Dance, Dance, Revolution. He spends hours at it. How many seconds is that?
Write a program that asks the user for the number of hours and minutes, and displays the number of seconds. Here’s an example of what happens when the program runs:



The formula is:
seconds = hours * 3600 + minutes * 60
Use this template. Add your own JavaScript:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Seconds</title>
<script type="text/javascript">
$(document).ready(function() {
$("#compute_seconds").click(function(){
Your code here.
});
});
</script>
<body>
<p>
<button type="button" id="compute_seconds">Compute</button>
</p>
</body>
</html>
Upload your solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
Here’s the code again:
var number, price, total;
number = prompt('How many brain chew toys?');
price = prompt('Price each?');
total = number * price;
alert('Total: $' + total);
Figure 2 (again). Some code
We could write the code without variables:
alert('Total: $' + prompt('How many brain chew toys?') * prompt('Price each?'));
Figure 3. Evil code
Which do you prefer? With or without variables?
The second one is less typing.
That’s true.
But it’s hard to understand. When I read it, by the time I’m half way through, I’ve forgotten what happened at the start.
Good point!
Renata’s right. It’s easier to deal with things in small chunks, rather than combining everything into one complex mess.
CC said something important there. It’s easier on your brain to break off a small piece of a problem, and solve that, then another small piece, then another. Try to keep everything in your brain at once, and your head will explode.
Variables let you do things in small steps. Do a step, put the results in a variable. Do another step, results into another variable. Until you’re done.
This code…
var number, price, total;
number = prompt('How many brain chew toys?');
price = prompt('Price each?');
total = number * price;
alert('Total: $' + total);
Figure 2 (again). Some code
... breaks the task into small pieces. This code…
alert('Total: $' + prompt('How many brain chew toys?') * prompt('Price each?'));
Figure 3 (again). Evil code
... mixes everything up. As a beginner, write your code in small chunks. Your brain will thank you.
Variables are used to accumulate totals and counts. This is a variant of keep-data-for-later.
Suppose you work at a carnival. You run the ferris wheel.

People buy tokens to go on rides. Your ride costs one token. When someone climbs into your ferris wheel, they drop a token in a pot:

The number of tokens in the pot gets larger as the day goes on. A token for each new rider. The pot accumulates tokens.
A variable can be like that pot. The variables sits in memory, with a value in it:
| ferris_count |
|---|
| 12 |
A new rider comes along, and the value goes up:
| ferris_count |
|---|
| 13 |
Here’s a button you can click when a new person goes on the ride. Try it a few times.
Here’s the code:
<script type="text/javascript" >
$(document).ready(function(){
var ferris_count = 0;
$("#ferris_button").click(function(){
ferris_count = ferris_count + 1;
alert("Ferris wheel count: " + ferris_count);
});
});
</script>
<p>
<button type="button" id="ferris_button">Count</button>
</p>
Figure 4. The ferris pot
Line 3 creates a variable called ferris_count in the computer’s memory, and puts zero in it. This “initializes” the variable, giving it a starting value.
The line is outside the click function. This is important! Line 3 only runs once, when the page has been loaded. We only want to set ferris_count to zero once. More on that later.
When the button is clicked, lines 5 and 6 run. Here’s line 5:
ferris_count = ferris_count + 1;
This says “Get the value from ferris_count, add 1 to it, and put the result into ferris_count.” So, if ferris_count has 0 in it before line 5 is run, it would have 1 in it after line 5 has run. If it had 18 before, it will have 19 after. This is what we want: click the button, the variable goes up by one.
As it turns out, “add 1 to a variable” is common in programming. So there’s a shortcut in JavaScript:
ferris_count ++;
This does the same thing as ferris_count = ferris_count + 1;.
Line 6 shows the current value of the variable:
alert("Ferris wheel count: " + ferris_count);
You can watch the program as it runs. Click the Count button to get started. You can run the statements in the click() event one at a time, and watch what happens.
Here’s the ferris wheel code again:
<script type="text/javascript" >
$(document).ready(function(){
var ferris_count = 0;
$("#ferris_button").click(function(){
ferris_count = ferris_count + 1;
alert("Ferris wheel count: " + ferris_count);
});
});
</script>
<p>
<button type="button" id="ferris_button">Count</button>
</p>
Figure 4 (again). The ferris pot
Line 3 declares (creates) the variable:
var ferris_count = 0;
Something important: the variable is created outside the click function.
var ferris_count = 0; ← Variable created.
$("#ferris_button").click(function(){
ferris_count = ferris_count + 1; ← Variable used.
..
});
Why? It has to do with something called “variable scope.” It’s a complex topic, but we don’t care about all the details. I’ll give you just two simple rules. Here’s the first one:
Use global variables when you want to count or total something. Declare the variables outside any function.
That’s what the ferris wheel example does. We want the browser to remember how many button clicks there were, so the next click adds one to that value. So:
var ferris_count = 0; ← Variable created.
$("#ferris_button").click(function(){
ferris_count = ferris_count + 1; ← Variable used.
..
});
ferris_count is declared outside the click() function. The memory for ferris_count is allocated when the page loads. It stays there, even when the user is not clicking on anything.
Suppose we mess it up:
<script type="text/javascript" >
$(document).ready(function(){
$("#ferris_button").click(function(){
var ferris_count;
ferris_count = ferris_count + 1;
alert("Ferris wheel count: " + ferris_count);
});
});
</script>
<p>
<button type="button" id="ferris_button">Count</button>
</p>
Figure 5. The ferris pot – brokeh
ferris_count is declared inside the click() function this time. (I left off the = 0 part (it used to be var ferris_count = 0), since that will just set it to zero each time.)
When the user clicks, line 4 will create the variable. Line 5 will add to it. Line 6 shows it. Line 7 ends the function, and destroys the variable!
That’s right. Variables declared inside a function are removed from memory when the function ends.
Click this button to run Figure 5:
What the…? The result varies between browsers. This is what I got in Firefox:

Figure 6. Brokeh output
NaN means “not a number.” Let’s not worry about why the browser does that. The point is, it doesn’t work.
Variables declared outside any function are called “global variables.” They are created when the page loads, and vanish when another page loads.
Variables declared inside a function (like a click() function) are called “local variables.” They are created when the function starts, and vanish when the function ends. Each time the click() function runs, local variables are created and destroyed.
Remember the first scope rule:
Use global variables when you want to count or total something. Declare the variables outside any function.
Now let’s talk about the second scope rule.
Suppose you quit the ferris wheel job. You get a new job at a local movie theater, counting ticket sales. Adults and children are counted separately.
Here are three buttons. One to count adult tickets, one to count child tickets, and the third to show how many of each type have been sold. Oh, and a fourth button to reset everything back to zero.
Play around with the buttons for a while.
Now let’s peek inside the code, and check out the variables in memory.
Here’s the code:
<script type="text/javascript">
$(document).ready(function() {
var adult = 0;
var child = 0;
$("#sold_adult").click(function(){
adult ++;
});
$("#sold_child").click(function(){
child ++;
});
$("#show_sales").click(function(){
alert("Adults: " + adult + " Children: " + child);
});
$("#reset_tickets").click(function(){
adult = 0;
child = 0;
});
});
</script>
...
<button id="sold_adult" type="button">Sold adult ticket</button>
<button id="sold_child" type="button">Sold child ticket</button>
<button id="show_sales" type="button">Show sales</button>
...
<button id="reset_tickets" type="button">Reset</button>
Figure 7. The code
Lines 3 and 4 declare the two variables, adult and child. They are global variables, since both are declared outside any function. The variables are created in memory when the page loads, and removed when the page is unloaded.
Global variables are available to every function. For example, three separate click() functions use the variable adults.
Different functions can do different things to the same variable. The $("#sold_adult").click() function adds to adults. The $("#show_sales").click() function displays the value in adults. $("#reset_tickets").click() sets the variable back to zero.
This shows the second rule for variable scope:
Use global variables when you want to share data between functions.
Create a page that counts the donuts and muffins sold by a bakery. The page should look like this:

The user clicks the buttons to record sales. The third button shows the sales so far. For example, suppose the user clicks the donut button four times, and the muffin button three times. The user clicks the Show Sales, and sees:

You can start with this code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Bakery sales</title>
<script type="text/javascript">
$(document).ready(function() {
$("#sold_donut").click(function(){
});
$("#sold_muffin").click(function(){
});
$("#show_sales").click(function(){
});
});
</script>
</head>
<body>
<p>
<button id="sold_donut" type="button">Sold a donut</button>
</p>
<p>
<button id="sold_muffin" type="button">Sold a muffin</button>
</p>
<p>
<button id="show_sales" type="button">Show sales</button>
</p>
</body>
</html>
Upload your solution to your server, and enter the URL below.
(Log in to enter your solution to this exercise.)
On this page, you saw code that runs when the user does something, like clicks on a button. Let’s talk about that button clicking.
In this lesson, you’ll learn:
Suppose we want users to fill in a form on a Web site. We give instructions for filling out the form. But we don’t want the instructions to get in the way. The instructions will start out hidden, but users can show them if they want.
Try this page. Click on “Show instructions” and see what happens. (The “v” represents an image of a down arrow.)
An event is something that happens on a Web page, like a user clicking on text. Your code tells the browser what to do when the event happens.
Your browser knows about lots of events. Try this exercise.
Here are some elements: a button, some text, and an input field:
Some text
As you interact with them, they’ll generate events. The name of the event will appear to the right of each element. For example, if you rest the mouse cursor on the button:

Write down the names of the events that each element generates (e. g., “Button: mouse over”). Enter the events below, under Your solution.
Hint: There are four events each for the button and text, and five events for the field.
Note: This only shows you the most common events the elements can generate. There are a few more.
(Log in to enter your solution to this exercise.)
Let’s get back to the show-and-hide-help task. Here are two pieces of code. They’re not in JavaScript, just English.

Figure 1. Two pieces of code
These “pieces of code” are called functions. A function is code that’s a single unit, e. g., code that handles an event. In fact, functions that handle events are called event handlers. So Figure 1 is really:

Figure 2. Two functions
You’ll learn more about functions later.
Each function in Figure 2 is just a single line. That’s OK. Functions can be any length.
We want the browser to run the first function when the user clicks on “Show help v.” We want the browser to run the second function when the user clicks on “Hide help ^.” Here’s how we would put them together.

Figure 3. Two functions again
Here’s the general template for event handlers, that is, functions that run when an event is triggered:

Figure 4. Event template
“object” is the thing that the event happens to. “event” is the event’s name, like “click” or “mouse over.”
You can make functions do lots of stuff. Create things, erase things, hide things, show things, change the text of paragraphs, headings and other things, show popup messages to the user, ... lots of stuff.
Here’s an unfriendly program.

Figure 5. Evil program
When the user clicks on the help prompt, the browser runs the function. It would play a sound, erase the page, and popup a message.
You can have all sorts of fun with users.
They might not think it’s fun. Some people have no sense of humor.
Here’s another version:

Figure 6. Annoying program
Instead of erasing the page, it just hides it, and brings it back later.
Programmers get up to tricks like this. “Easter eggs” are things that are buried in programs, surprises for users. They’re usually harmless. For example, type this into the address bar of Firefox:
about:mozilla
What you see is a strange dig at Internet Explorer.
Try this:
about:robots
One more. This isn’t really an easter egg, it’s just the way the tech works.
chrome://browser/content/browser.xul
Firefox inside Firefox!
Enough distraction. Here’s the template again:

Figure 4 (again). Event template
This is actually not too far from real code. jQuery has a click() event, that fires when the user clicks on something. We can use that to trigger the state changes.
There’s one other jQuery event we’ll need. The browser doesn’t watch for all possible events. Instead, we tell it what events to watch for. Here are the event handlers again:

Figure 3 (again). Two functions again
When the page loads (that is, is shown to the user), we want the browser to set up these two event handlers. How? By adding them inside another event handler.

Figure 7. Page load event
jQuery has an event called ready(). The ready() event happens just after a Web page has finished loading, but before the user is allowed to interact with it. Usually you put initialization code in the ready() event. That’s code that runs once, to finish getting the page ready for the user.
Back to the show-hide-help example. This page.
Let’s write the HTML for the page. Most JavaScript code messes with HTML objects, like paragraphs.
<p>Please fill in this form:</p> <p>Show instructions v</p> <p>Hide instructions ^</p> <blockquote> Helpy help help. </blockquote> <p>FORM</p>
Figure 8. HTML
You can see the HTML objects the program will mess with: the help prompts that people will click on (lines 2 and 3), and the help message that will be shown and hidden (lines 4 to 6). You can see the page as it is so far.
How come I can see both help prompts?
We’ll change it in a moment, so that the user will see only one or the other.
So far, we’ve worked out what the program will do, and identified events that we will tie code to. The next step is to name things.
When you want to change something on a page, you need to be able to refer to it. The easiest way to do that is with the id attribute.
Here’s an example:
<blockquote id="instructions">Helpy help help.</blockquote>
Figure 9. The id attribute
An attribute is something you attach to an HTML tag, that modifies it in some way. There are many different attributes. For now, the only one we care about is id.
Make sure that every id is unique within a page. That is, there should only be one element with id of instructions on any page.
There’s another attribute called name. Don’t use it yet. It means something different.
Once we’ve given an element an id, we can mess with it. In our example, we need to give ids to:
click() eventsSo we’ll give ids to these three things. Here’s the code:
<p>Please fill in this form:</p> <p id="instructions_title_show">Show instructions v</p> <p id="instructions_title_hide">Hide instructions ^</p> <blockquote id="instructions"> Helpy help help. </blockquote> <p>FORM</p>
Figure 11. Giving HTML elements ids
There are four <p> tags, but only two have ids. Why?
We only need to attach ids to HTML elements we refer to in JavaScript code. We’ll attach code to “Show instructions” and “Hide instructions,” so they need ids. So do the instructions themselves, because they will be hidden and shown.
But our program doesn’t do anything with the first <p> tag. No events are attached to it, and our program doesn’t change it in any way. So, no need for an id.
So if you don’t need to, don’t attach an id?
Right. Sometimes you give HTML elements ids so you can style them with CSS, and that’s OK. But unless an HTML element is being used by JavaScript or needs to be styled by CSS, don’t give it an id.
OK, we’re ready to attach code to events.
Here’s the entire page so far.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Instructions</title>
</head>
<body>
<p>Please fill in this form:</p>
Show instructions v
Hide instructions ^
<blockquote id="instructions">
Helpy help help.
</blockquote>
<p>FORM</p>
</body>
</html>
Figure 12. The page so far
Note that we’ve loaded jQuery in line 5.
I usually don’t write programs all at once. Instead, I write just a piece, and then try it out. This is a good practice, since it limits the number of things that can go wrong.
Let’s try that. We’ll start by hiding the instructions when the page loads.
<script type="text/javascript">
$(document).ready(function() {
$("#instructions").hide();
});
</script>
Figure 13. Hiding instructions
Remember, everything between $(document).ready(function() { and }); runs once the page has been loaded.
The $("#instructions") in line 3 tells jQuery to find some elements on the page. Which ones? The ones that have an id of instructions. Be sure to include the #. This is what tells jQuery to look at the id attribute, and not some other attribute. Leaving out the # is a common error.
There should be only one element with an id of instructions. If there is more than one, browsers can start acting strangely.
The rest of the statement tells jQuery what to do with the elements it finds. .hide() tells jQuery to hide them.
In English, $("#instructions").hide(); is:
Find all the elements with an
idofinstructions, and hide them.
The ; at the end of the line tells JS that this is the end of the statement. It’s optional, but good practice.
You can try the page so far.
We could write the rest of program in one step, but we won’t. Let’s just get the event binding to work. Remember that “binding” ties code to an event.
Let’s write it so that clicking on the instruction title shows a simple message. Here’s the new code.
<script type="text/javascript">
$(document).ready(function() {
$("#instructions").hide();
$("#instructions_title_show").click(function() {
alert("Clicky clicky 1.");
});
$("#instructions_title_hide").click(function() {
alert("Clicky clicky 2.");
});
});
</script>
Figure 14. Eventing
Pattern: Run code on click
You can try it.
$("#instructions_title_show") means “find everything with an id of instructions_title_show” (don’t forget the #). There is only one thing with that id. .click(function() { means “Here’s what to do with the user clicks on it.”
What happens when the user clicks? S/he gets a message. Try it if you haven’t already.
For the next step, We’ll do this:
<script type="text/javascript">
$(document).ready(function() {
$("#instructions").hide();
$("#instructions_title_show").click(function() {
$("#instructions").show('fast');
});
$("#instructions_title_hide").click(function() {
$("#instructions").hide('fast');
});
});
</script>
Figure 15. Toggling visibility
You should try it.
Again, $("#instructions") means “Find everything with an id of instructions. .show('fast') means “Show it quickly.” The speed can be 'medium' or 'slow' as well, or we can leave it out, which would be .show().
You can also do something like .show(5000). This will run the effect over 5,000 milliseconds (ms). An ms is 1,000th of a second, so the effect would take 5 seconds to complete. ms is a common unit in computing.
Hmm, can you guess what hide('fast') does?
Start with this code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Secret of Life</title>
<script type="text/javascript">
$(document).ready(function() {
});
</script>
</head>
<body>
<p id="secret_instructions">Click me to learn the secret of a happy life.</p>
<h1 id="secret">Dogs!</h1>
</body>
</html>
Add code to hide secret when the page first loads, and then show it when the user clicks on secret_instructions.
Upload your solution to your server, and enter its URL below.
(Log in to enter your solution to this exercise.)
We’re almost done.
Right now, we have both help prompts showing:

Figure 16. Both prompts
We want to hide one of them when the page loads. When the user clicks, we want to change which of the help prompts is visible.
This will do it:
<script type="text/javascript">
$(document).ready(function() {
//The page has loaded.
//Hide the instructions.
$("#instructions").hide();
//Hide one of the help prompts.
$("#instructions_title_hide").hide();
$("#instructions_title_show").click(function() {
//User has clicked on the "Show" prompt.
//Switch the help prompt.
$("#instructions_title_show").hide();
$("#instructions_title_hide").show();
//Show the instructions.
$("#instructions").show('fast');
});
$("#instructions_title_hide").click(function() {
//User has clicked on the "Hide" prompt.
//Switch the help prompt.
$("#instructions_title_hide").hide();
$("#instructions_title_show").show();
//Hide the instructions.
$("#instructions").hide('fast');
});
});
</script>
...
<body>
<p>Please fill in this form:</p>
<p id="instructions_title_show">Show instructions v</p>
<p id="instructions_title_hide">Hide instructions ^</p>
<p id="instructions">These are the instructions.</p>
<p>FORM</p>
</body>
Figure 17. Prompt visibility
You can try this page.
Line 7 hides the “Hide help ^” prompt. It is inside the ready() event. It runs when the page loads. So when the user first sees the page, only the “Show help v” prompt will be visible.
Lines 11 and 12 run when the user clicks on the “Show” prompt. They change which help prompt is visible.
Two other things to notice. First, there are lots of comments. They all begin with //. They explain how the program works.
Second, the code is indented. Each time there is a new tag or brace ({) opened, I added two spaces. Some people use four spaces; do whatever you like.
The browser does not care about indenting. It will not affect the way the code runs. But it makes the code much easier for people to read.
Especially humans. They’re easily confused.
Here’s Figure 16 again:

Figure 16 (again). Both prompts
Another option is to have just one click target, like this:

Figure 18. One click target
This isn’t as good for the user, since the prompt (show/hide) is less specific than two separate prompts. But the code is easier to write:
<script type="text/javascript">
$(document).ready(function() {
//The page has loaded.
//Hide the instructions.
$("#instructions").hide();
$("#instructions_show_hide").click(function() {
//User has clicked on the "Show/hide" prompt.
//Toggle the instructions.
$("#instructions").toggle('fast');
});
});
</script>
...
<body>
<p>Please fill in this form:</p>
<p id="instructions_show_hide">Show/hide instructions</p>
<p id="instructions">These are the instructions.</p>
<p>FORM</p>
</body>
Figure 19. Toggle function
Look at line 9:
$("#instructions").toggle('fast');
Instead of show or hide, there’s toggle. If something is showing, toggle will hide it. If something is hiding, toggle will show it. It switches back and forth.
You can try the page.
Try this version of the page. Notice that the mouse cursor changes to a hand when the user moves it over one of the help prompts. This gives the user a hint that the element is clickable.
I added the following CSS to the page:
#instructions_title_show:hover,
#instructions_title_hide:hover {
cursor: pointer;
}
Figure 20. Styling the cursor
There are several new things here. First, there’s the # in front of the selectors. This is same thing that jQuery uses. #instructions_title_show means “find the thing with the id of instructions_title_show, and apply the style.” In fact, jQuery borrowed this syntax from CSS.
The second new thing is the :hover. This is called a pseudo-class. :hover means “apply the styles when the mouse is on the element.” You can apply any styles at all. You can change the font, color, background color, whatever. For example, you could do this:
<style type="text/css">
#instructions_title_show:hover {
cursor: pointer;
font-weight: bold;
font-size: 24px;
color: red;
background-color: yellow;
}
</style>
Figure 21. Going too far
You could do this, but I wouldn’t recommend it. The point is, you can change anything.
Another new thing in Figure 20 is the cursor style. This changes the mouse cursor. There are lots of cursors you can use. See the SitePoint reference page for a list.
Finally, you can apply the same styles to more than one type of thing at the same time. This:
selector1, selector2 {
style rules;
}
applies the rules to all the items selected by selector 1, and all of the items selected by selector 2. For example, let’s say I wanted to make all <h1>s, <h3>s, and <h5>s dark red, and all <h2>s, <h4>s, and <h6>s dark green. Here’s what I would do:
<style type="text/css">
h1, h3, h5 {
color: #660000;
}
h2, h4, h6 {
color: #006600;
}
</style>
Figure 22. Heading styles
Make sure you use a comma (,) to separate the items. If you leave it out, the rule won’t work.
Wow, that took a long time. For such a simple program.
Only because this was our first program. Every program we write will use events and such in the same way. So we won’t have to go as slowly.
Write a program to show the first part of a dog joke:

When the user clicks on “Show/hide the answer,” the answer appears:

Upload you solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
On this page, you learned how to:
All cool stuff!
Let’s see how you can change the actual text of an element, and the CSS that’s applied to it.
In the previous lesson, you learned how to add interactive help to a Web page. Let’s see how you can make more changes to a page.
By the end of this lesson, you should:
<p>.How do we create this page? First, we need to attach a .click() event to each of the answers.

Figure 1. Quiz events
The code attached to the click events change the text of the right/wrong message. Three of them show the “Wrong” message. One of them shows the “Right” message.

Figure 2. Right/wrong messages
We could write separate event handlers for all four answers (remember that an event handler is code attached to an event). But there’s an easier way.
Let’s start with this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Instructions</title>
<style type="text/css">
body {
background-color: #FFFFEE;
font-family: Verdana, sans-serif;
font-size: 14px;
}
.right, .wrong {
cursor: pointer;
}
#result {
font-weight: bold;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
Program goes here.
});
</script>
</head>
<body>
<h1>Quiz</h1>
<p>What is 4 x 7?</p>
<p>Please click on the right answer.</p>
<p class="wrong">a. 14</p>
<p class="wrong">b. 47</p>
<p class="right">c. 28</p>
<p class="wrong">d. I will never need to know.</p>
<p id="result"></p>
</body>
</html>
Figure 3. Getting started
The result paragraph (line 34) is where the result will go, with the “Right” or “Wrong” message. That’s why the <p> has an id: our code needs to refer to it.
Our code needs to refer to the answers as well, so it can attach event handlers. Look at lines 30 to 33, and you’ll see something different. I used class instead of id. Why?
Remember that ids have to be unique. There can only be one element on a page with an id of dog. Not so with class. There can be an unlimited number of elements with the same class name. I can write one event handler for anything with a class of wrong, and it will apply to all elements with that class.
Let’s look at the CSS. The rule in lines 8 to 12 sets up some defaults for the page. Since all of the page’s content is inside the <body>, the rule applies to all elements.
The rule in lines 13 to 15 has two selectors: .right and .wrong. The selector .right says, “Apply this rule to all elements that have a class of right.” Remember to use # for id, and . for class. The selector .wrong says, “Apply this rule to all elements that have a class of wrong.” There’s a comma (,) between the selectors, so the rule applies to both classes.
The rule itself (line 14) sets the mouse cursor to a pointing hand.
Finally, the rule in lines 16 to 18 applies to the element with the id of result. A # means “look at id.” A . means “look at class.”
Let’s see if I have this right. You have an event handler, that’s going to do something. If you want to attach that handler to just one thing on the page, use id. Is that right?
Yes.
But if you want to attach the same handler to more than one thing, use class.
Right!
And you do the same with CSS rules, that change the look of things. If a particular look is going to be used on just one thing, like just one <p>, use an id. That means <p id="whatever"> in the HTML, and #whatever in the CSS.
Indeed.
But if you want to give more than one thing the same look, use <p class="whatever"> in the HTML and .whatever in the CSS.
Yes, you’ve got it! W00fs for both of you!
OK, let’s look at the code. We’ll need events for both the classes.
<script type="text/javascript">
$(document).ready(function() {
$(".right").click(function() {
Something
});
$(".wrong").click(function() {
Something else
});
});
</script>
Figure 4. Events
The first one will apply to the one element that has a class of right. The second one will apply to the three elements that have a class of wrong.
Could you have used an id for right, since there is only one?
Yes, I could. But a future question might have more than one right answer. A question like, “Which of these people signed the American Declaration of Independence?” might list several names, more than one of which might be correct. I used class just in case.
In the hiding help example on the previous page, we put in two different help prompts. We could have included two different versions of the result paragraph, one with the “Right” message, and the other with the “Wrong” message.
I didn’t do that here, because I want to show a different way of doing things. We just have one place to show the result:
<p id="result"></p>
What we’ll do is change the content of that, depending on whether the answer is right or wrong.
Here’s the code:
<script type="text/javascript">
$(document).ready(function() {
$(".right").click(function() {
$("#result").text("Right! W00f!");
});
$(".wrong").click(function() {
$("#result").text("Sorry, that's wrong.");
});
});
</script>
Figure 5. The final code
text() will set the content of an element. This:
$("#result").text("Right! W00f!");
means “Find all elements with an id of result, and set their text to ‘Right! W00f!’.” Only one element has an id of result. As always, don’t forget to add the # when dealing with ids, and . for classes.
Any text can go inside text(). It can be a fixed message, like this example. But it doesn’t have to be.
Try this page. Click on the “Add” messages to add different types of cars to the train.
This is different from the last one, in that the output is always growing. When you click on an “Add,” the output doesn’t get replaced with a new value. Instead, some new text is added to what is already there.
Here is the page without the JavaScript:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Make a train</title>
<style type="text/css">
body {
background-color: #FFFFEE;
font-family: Verdana, sans-serif;
font-size: 14px;
}
#add_passenger_car,
#add_freight_car {
cursor: pointer;
}
#train {
font-weight: bold;
}
</style>
<script type="text/javascript">
</script>
</head>
<body>
<h1>Make a train</h1>
<p id="add_passenger_car">Add passenger car</p>
<p id="add_freight_car">Add freight car</p>
<h2>Your train</h2>
<p id="train">Engine</p>
</body>
</html>
Figure 6. Start of the train
Lines 26 and 27 are the things you can click on. They need ids, because we need to bind code to their click() events.
Line 29 is the output. It needs an id as well, so we can change it.
Here is the JavaScript:
<script type="text/javascript">
$(document).ready(function() {
$("#add_passenger_car").click(function() {
$("#train").text( $("#train").text() + ' passenger' );
});
$("#add_freight_car").click(function() {
$("#train").text( $("#train").text() + ' freight' );
});
});
</script>
Figure 7. Train code
Look at line 4, which adds a passenger car to the train. Read it from the inside out:

That’s what the browser does when it runs JavaScript. It does the stuff inside parentheses (the () ) first. So the first thing the browser runs is:
$("#train").text()
There’s nothing inside the (). When it sees that, jQuery gets the current text. So, what .text() does depends on whether there is something inside the ():
$("#train").text("W00f")sets the text to W00f.
$("#train").text()gets the text, whatever it is.
Now let’s look at some more of line 4

This gets the text from train, and appends “ passenger” to the end of it. So if train had “Engine” in it, we would end up with “Engine passenger”. If train had “A zombie will eat every” in it, we would end up with “A zombie will eat every passenger”.
This line also shows that you can mix single quotes (') and double quotes ("). Just match pairs. So if you start with a ", close it with a ".
Now let’s look at all of line 4:
$("#train").text( $("#train").text() + ' passenger' );
This says: Get the text of the element with an id of train, add “ passenger” onto the end of it, and put the result into the element with an id of train.
Change the train example. Add “Clear” below the two “Add” controls. Clicking on “Clear” sets the train back to just “Engine”.
Hint: Ask yourself, “What changes on the page when the user clicks Clear?”
Upload your solution to your server, and put its URL below.
(Log in to enter your solution to this exercise.)
Oblivion is one of my favorite computer games. It’s a mixture of a role-playing game and a first-person shooter. I’ve waste…, er, invested way too much time on it.
The game is set in the nation of Cyrodiil. Cyrodiil has a bunch of cities with strange names. Let’s make a Cyrodiil cities quiz. But this one will be a little different from the last one we did.
Try the page. Click on the city names, to learn whether each one is real or fake.
Here’s the HTML and CSS:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Oblivion cities</title>
<style type="text/css">
body {
background-color: #FFFFEE;
font-family: Verdana, sans-serif;
font-size: 14px;
}
.real, .fake {
cursor: pointer;
}
.highlight {
font-size: 16px;
font-weight: bold;
color: #660000;
}
</style>
<script type="text/javascript">
JavaScript goes here.
</script>
</head>
<body>
<h1>Oblivion cities</h1>
<p>
Which of the following are cities in Cyrodiil?
Guess whether each one is real (in the game) or
fake. Click on it to see the answer.</p>
<ul>
<li class="fake">Arcasha</li>
<li class="real">Kvatch</li>
<li class="real">Cheydinhal</li>
<li class="fake">Xenithar</li>
<li class="fake">Vercingetorix</li>
<li class="real">Skingrad</li>
</ul>
<p id="real_city">Real</p>
<p id="fake_city">Fake</p>
</body>
</html>
Figure 8. Cities quiz
The cities are in a list, from lines 33 to 40. Each city has a class of either real or fake. When the user clicks on a city, we want to highlight “Real” (line 41) if it’s a real city in the game, or “Fake” (line 42) if it’s not.
Let’s write the JavaScript. I start with the ready() event.
$(document).ready(function() {
});
Figure 9. ready() event
This is run when the page has loaded.
I’ll bind code to the click() events of the real and fake items:
$(document).ready(function() {
$(".fake").click(function() {
});
$(".real").click(function() {
});
});
Figure 10. Binding code to events
Clicking on an element with the class fake will run the code at line 3. Clicking on an element with the class real will run the code at line 6.
If the city is real, we want to highlight “Real,” and make sure that “Fake” is not highlighted. How to highlight something? A clue is in the CSS:
body {
background-color: #FFFFEE;
font-family: Verdana, sans-serif;
font-size: 14px;
}
...
.highlight {
font-size: 16px;
font-weight: bold;
color: #660000;
}
Figure 11. CSS to highlight something
The font size is normally 14 pixels (line 4). Its normal color is black; that’s the browser’s default, and nothing in the CSS changes that for regular text.
But if we apply the class highlight to something, its text will get larger, bold, and dark red. So we can highlight something by giving it the class highlight. Removing the class will set it back to regular text.
jQuery gives us addClass() and removeClass(). They, er, add and remove classes. Here’s the final code:
$(document).ready(function() {
$(".fake").click(function() {
$("#fake_city").addClass("highlight");
$("#real_city").removeClass("highlight");
});
$(".real").click(function() {
$("#real_city").addClass("highlight");
$("#fake_city").removeClass("highlight");
});
});
Figure 12. Code for changing classes
When a user clicks on an element with the class fake (line 2), the element fake_city is give the highlight class (line 3), and the highlight class is removed from real_city (line 4). If the class wasn’t there, no harm is done.
Create a page like the one on cities in Cyrodiil. It will list words that are from HTML, CSS, or JavaScript/jQuery. Click on each word, and the page will highlight the tech that name is from.
Upload your solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
id for JavaScript, and class for CSSHere’s another way to do the cursor style in Figure 6:
Remove this:
#add_passenger_car,
#add_freight_car {
cursor: pointer;
}
...
<p id="add_passenger_car">Add passenger car</p>
<p id="add_freight_car">Add freight car</p>
Replace with:
.car {
cursor: pointer;
}
...
<p id="add_passenger_car" class="car">Add passenger car</p>
<p id="add_freight_car" class="car">Add freight car</p>
Figure 13. id and class
Here, the <p>s have both an id and a class. The id is used in the JavaScript, and the class is used in the CSS.
It can be convenient to do this sometimes. Suppose I wanted to change several attributes of the text “Add passenger car” at once. Maybe make it bold, green, and in a different typeface. Whatever. I could define another class called supercar.
.supercar {
...
}
In JavaScript:
$("#add_passenger_car").removeClass("car");
$("#add_passenger_car").addClass("supercar");
This can be shortened to:
$("#add_passenger_car").removeClass("car").addClass("supercar");
When I do this, I usually format it like this:
$("#add_passenger_car")
.removeClass("car")
.addClass("supercar");
Makes it easier to read.
So, if you want to change the look of an element in a JavaScript program, it’s often easier to define both a class and an id. The look is defined entirely by the class, and never by the id. You can easily mess with the class, using addClass and removeClass.
In this lesson, you learned some more JavaScript/jQuery:
text("stuff") will set the text of an element.text() will get the text of an element.addClass() adds a CSS class to an element.removeClass() removes a CSS class from an element.Let’s see how we can get more data from the user, other than just clicks.
You know how to show and hide elements, change their text, and add and remove classes. You know how to tie these things to click events.
Now lets ask users questions, and do things with their answers. Even more w00f!
There are lots of ways to get data from users. The most familiar way is to use Web forms, so let’s start there.
Form processing is quite complicated, so we’re not going to look at it all here. In fact, we’re going to take just a couple of pieces, and use them in ways that some Webers will object to.
Calm down, Webers! We’ll get to correct form processing later. But for now, let’s keep it simple, so we can start exploring.
Forms are created with HTML tags. We’ll use two of them here: the <input> tag and the <button> tag.
The <input> tag is used for a lot of different things in HTML. We’ll just use one version of it, the one that creates text input fields.
Here’s an example:
<input type="text" id="my_field">
Here’s what this looks like in your browser:
The type attribute tells the browser what type of field you want. There are check boxes, radio buttons, and others. Let’s stick to text for now.
The other tag is <button>. Here’s an example:
<button type="button" id="go">Click me!</button>
Here’s what it looks like in your browser:
Buttons looks different on other sites. I’ve used CSS to make CoreDog’s buttons match the rest of the CoreDogs look. Part of the branding of this site.
There are two types of buttons, regular buttons and submit buttons. We’re using the regular buttons here. That’s what type="button" tells the browser.
The text inside the tag – Click me! or whatever – supplies the button’s caption, that is, the text on the button.
Time for the obligatory “hello world” example. We’ll do it in stages.
Let’s do the first step, just make the HTML and a button that does something. Please have a look at this page.
Here is the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Hello world!</title>
<script type="text/javascript">
$(document).ready(function() {
$("#user_name_output").hide();
$("#go").click(function() {
alert('You clicked me!');
});
});
</script>
</head>
<body>
<p>
Please type your name below and click the button.
<input type="text" id="user_name_input">
<button type="button" id="go">Go!</button>
</p>
<h1 id="user_name_output"></h1>
</body>
</html>
Figure 1. Starting “Hello world!”
Line 19 creates a text input field. Line 20 creates a button right next to it. Line 22 gives a place for output.
The code in lines 9 to 12 is run when the page is ready. Line 9 hides the output area. Line 10 sets up an event handler, run when the user clicks the button.
So far, so good. Let’s add the rest of the code. When the user clicks the button, what we want to happen is this:
Here’s some code:
$("#go").click(function() {
//Get the user's name.
user_name = $("#user_name_input").val();
//Add it to the output.
$("#user_name_output").text("Hello " + user_name + "!");
//Show the output.
$("#user_name_output").show('slow');
});
Figure 2. Code
Please try it.
Lines 2, 4, and 6 are comments. Any line in your JavaScript that starts with // is ignored by your browser. The comments help explain what the code is doing.
Adding comments is good practice. When someone needs to change what the code on the page does, s/he will first read the comments to figure out how the current code works. Good comments make that task easier.
Line 3 gets whatever the user typed. $("#user_name_input").val() finds the field with the id of user_name_input, and gets its contents. val() is an attribute of form fields. It returns the contents of the field.
What does line 3 do with the value? It puts it in a variable.
user_name = $("#user_name_input").val();
A variable is a temporary holding place in the computer’s memory. When the browser sees user_name for the first time, it grabs some memory and labels it user_name.
The = in line 3 says “Take the value on the right, and put it into the variable on the left.” So line 3 takes the value in the text field, and stores it in the variable user_name.
Look at line 5:
$("#user_name_output").text("Hello " + user_name + "!");
"Hello " + user_name + "!" says to take the text “Hello “, put the contents of the variable user_name on the end, and then put the text “!” on the end of that.
Huh!?
Let’s take a side trip, to see how this works.
user_name = "Tim";
alert("user_name");
alert(user_name);
alert("user_name: " + user_name);
alert(user_name + "Taylor");
Figure 3. Variables and constants
Line 1 shows the difference between variables and constants. user_name is a variable. As just explained, a variable is a temporary storage place in the computer’s memory for some data. You can put data into it, like Tim, or Lenny, or Katherine.
"Tim" is a constant. It will always be, well, "Tim". The quotes ("") are JavaScript’s way of representing fixed text.
Line 2 is:
alert("user_name");
It outputs a constant. "user_name" is a fixed value that will never change. This does not refer to the variable user_name. "user_name" means the exact text "user_name", just as "Renata likes treats" refers to the exact text "Renata likes treats".
On the other hand, line 3 outputs the contents of the variable user_name.
alert(user_name);
The line doesn’t have quotes around user_name. The browser says to itself, “Self, user_name must be a variable. I’ll get its value from memory, and show whatever that value is.”
Here’s a picture of these two lines in action.

Figure 4. A variable and a constant
The first line outputs whatever is between the quotes exactly as is. The second line fetches the contents of the variable user_name from memory, and outputs that.
Here’s Figure 3 again.
user_name = "Tim";
alert("user_name");
alert(user_name);
alert("user_name: " + user_name);
alert(user_name + " Taylor");
Figure 3 (again). Variables and constants
Let’s look at line 4. It takes the exact text user_name: (with a colon and a space at the end), appends the contents of the variable user_name, and outputs that.

Figure 5. Appending a constant and a variable
Line 5 takes the contents of variable user_name and appends Taylor. So it outputs Tim Taylor.

Figure 6. Tim Taylor
Got it? A variable is a piece of memory with a name. A constant is a fixed value. Text constants – often called string constants – have quotes around them. Single quotes will also work, like ‘CC’.
Here’s the “Hello world!” program again.
$("#go").click(function() {
//Get the user's name.
user_name = $("#user_name_input").val();
//Add it to the output.
$("#user_name_output").text("Hello " + user_name + "!");
//Show the output.
$("#user_name_output").show('slow');
});
Figure 2 (again). Code
So, in line 5, "Hello " + user_name + "!" tells the browser to take the constant “Hello “, append the contents of the variable user_name, and append the constant “!”.
If user_name has Renata in it, the result would be Hello Renata! If user_name has Larry the crazy pickle in it, the result would be Hello Larry the crazy pickle!
What happens to that text? It’s inserted into the element with the id of user_name_output.
Don’t forget the #s in all of this. The code won’t work without them. Computers are picky.
Finally, line 7 shows the element with the id of user_name_output.
Try this page, but don’t look at the source code. See if you can reproduce it.
Hint: Start by copying the “Hello world!” code, and making another text field.
Upload your solution to your server. Add the URL below.
(Log in to enter your solution to this exercise.)
On this page, you learned how to get some data from the user and show it. Let’s make a small change to improve a form’s usability.
You know how to show an input field, and get data from the user. Let’s improve the page’s usability.
By the end of this page, you should know how to use focus() to improve a page’s usability.
Please try this page. We’ll use it for this lesson and the next.
Here’s the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Favorite Game</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#game_in").focus();
$("#go").click(function() {
user_game = $("#game_in").val();
$("#game_out").text(user_game);
});
});
</script>
</head>
<body>
<h1>Favorite Game</h1>
<p>Please enter the name of your favorite game
(e.g., fetch, frisbee, chewing shoes). Then click the button.</p>
<p>Game:
<input type="text" id="game_in">
<button type="button" id="go">Go</button>
</p>
<p>Favorite game: <span id="game_out"></span></p>
</body>
</html>
Figure 1. Starting the game
Let’s look at the JS code:
<script type="text/javascript">
$(document).ready(function() {
$("#game_in").focus();
$("#go").click(function() {
user_game = $("#game_in").val();
$("#game_out").text(user_game);
});
});
</script>
Figure 2. The JS code
Most of it is familiar. There’s ready(), click(), val(), and text(). But what’s that focus() in line 9? Line 9 is in the ready() event, so it runs when the page loads.
focus()?To see what focus() does, let’s look at another version of the page. It has the following code:
<script type="text/javascript">
$(document).ready(function() {
// $("#game_in").focus();
$("#go").click(function() {
user_game = $("#game_in").val();
$("#game_out").text(user_game);
});
});
</script>
Figure 3. Modified JS code
In this version, I’ve commented out line 9. That’s the only difference.
OK, let’s compare them. Follow these instructions carefully. Don’t do anything extra. Not even a single click.
You should see this:

Figure 4. With focus()
Now do this:
This is what you should see:

Figure 5. Without focus()
Huh!? Where did the barking go?
It has to do with the focus. Watch this movie:
Figure 6. About focus()
Here’s the code again:
<script type="text/javascript">
$(document).ready(function() {
$("#game_in").focus();
$("#go").click(function() {
user_game = $("#game_in").val();
$("#game_out").text(user_game);
});
});
</script>
Figure 2 (again). The JS code
Line 9 is bound to the ready() event. It runs when the page loads. It sets the focus to the input field, so the user is ready to type. Try the page, and you’ll see that the input cursor is in the field.
Without line 9, the user has to click on the field before s/he can type into it. If the user doesn’t click on the field, and just starts typing, the data is lost. The user’s keystrokes go somewhere, but not into the field.
Line 9 makes the page more usable. That is, it makes it easier for the user to do a task. Usability is important on the Web. Webers think about work flow, that is, the sequence of actions needed to do a task. If they can eliminate steps from the work flow, they will.
The thing we did in line 9 is common. Try going to Google’s home page. Where is the cursor?
Try going to Bing. Where is the cursor when the page loads?
Try Twitter. After you have logged in, where is the cursor?
We’ll talk more about usability as we go.
Change your Hello world solution. When the page loads, the cursor should be in the first name.
Upload your solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
You learned how to use focus() to improve a page’s usability.
Let’s do some styling to change the look of input fields.
You know how to show an input field, and get data from the user. Let’s improve the way things look.
By the end of this page, you should:
Please try this page again. It’s the one we used in the previous lesson.
Here’s the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Favorite Game</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#game_in").focus();
$("#go").click(function() {
user_game = $("#game_in").val();
$("#game_out").text(user_game);
});
});
</script>
</head>
<body>
<h1>Favorite Game</h1>
<p>Please enter the name of your favorite game
(e.g., fetch, frisbee, chewing shoes). Then click the button.</p>
<p>Game:
<input type="text" id="game_in">
<button type="button" id="go">Go</button>
</p>
<p>Favorite game: <span id="game_out"></span></p>
</body>
</html>
Figure 1. Starting the game
The page is quite plain:

Figure 2. Plain page
Let’s add some styling to create this:

Figure 3. Styled page
You can try the page. Here’s the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Favorite Game</title>
<link type="text/css" rel="stylesheet" href="game2.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#game_in").focus();
$("#go").click(function() {
user_game = $("#game_in").val();
$("#game_out").text(user_game);
});
});
</script>
</head>
<body>
<h1>Favorite Game</h1>
<p>Please enter the name of your favorite game
(e.g., fetch, frisbee, chewing shoes). Then click the button.</p>
<p>Game:
<input type="text" id="game_in" size="20">
<button type="button" id="go">Go</button>
</p>
<p>Favorite game: <span id="game_out"></span></p>
</body>
</html>
Figure 4. Styled page code
Line 23 uses the size attribute to set the width of the input field to 20 characters.
But where are the styles? The background colors, the font changes, and such? There is no <style> tag in the file.
With JS, we saw that you can put your JS code in a separate file, and include it in your page. You can do the same thing with CSS: put the CSS rules in a separate file, and include them.
Here’s line 6:
<link type="text/css" rel="stylesheet" href="game2.css">
This tells the browser to include the CSS file game2.css.
Here’s the CSS file:
body {
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-size: 18px;
background-color: #FFFFF0;
}
h1 {
font-size: 28px;
font-weight: bold;
}
input {
background-color: #FFFF80;
}
button {
font-weight: bold;
background-color: #006600;
color: #FFFF40;
}
Figure 5. CSS file
The advantage is that you can reuse the same CSS across many HTML pages. Have one copy of the CSS file, and include it in all of the pages. Then, if you want to change, say, the background color of all of the HTML pages, change the one CSS file. Every HTML page that refers to the CSS looks different. W00f!
There’s not much new in the CSS rules themselves. Just the usual fonting and coloring. The only new things are on lines 12:
input {
and 16:
button {
They style all of the <input> and <button> tags on the page.
Notice how background-color works. It sets just the background color of the input fields and buttons.

Figure 6. <input> tag background color
You learned:
Let’s do some computations with data we get from users.
On this page, you’ll learn how to do computations based on data users enter. We’ll review some of the things we did earlier, just to make sure you got it. Baby steps, baby steps.
You’ll learn:
text().Let’s roll!
When you go to a restaurant in the US, it’s customary to tip a server (a waitress or waiter) 15% of the bill. So if your meal cost $30, the tip would be $30 × 15% = $4.50, and the total cost of the meal would be $34.50.
Let’s write a Web page to do that computation. Please try it now.
The word “computation” sounds sort of scary.
Hmm, yes, I can see that. But all it means here is doing some arithmetic, multiplying and adding. Even better: the computer does the work! You don’t have to.
Hey, I like that!
Here’s my starting page. Everything except the computation.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Tip</title>
<script type="text/javascript">
$(document).ready(function() {
$("#meal_cost").focus();
$("#compute_tip").click(function(){
alert("Tippy tip tip.");
});
});
</script>
</head>
<body>
<h1>Tip Computer</h1>
<p>
Meal cost:
<input type="text" id="meal_cost">
<button type="button" id="compute_tip">Compute</button>
</p>
<p>Tip: <span id="tip"></span></p>
<p>Total: <span id="total_cost"></span></p>
</body>
</html>
Figure 1. Starting the tip computer
Please try the code so far.
Most of the code should be familiar. Line 20 creates a text field. Line 21 creates a button.
Line 23 creates an output area to show the tip. It introduces a new tag: <span>. <span> is an inline tag. It can be inserted right into the middle of some content. <span> let us give an id to a spot on the page, so we can refer to that place in JavaScript code.
Line 24 is another output area. It also uses a <span> with, of course, a different id. Remember that ids should be unique within a page.
Let’s look at the JS.
$(document).ready(function() {
$("#meal_cost").focus();
$("#compute_tip").click(function(){
alert("Tippy tip tip.");
});
});
Figure 2. JavaScript from the first tip computer
Line 1 attaches some code to the ready() event. Lines 3 to 5 bind some code to the compute_tip button.
Line 2 sets the focus in the input field when the page loads. The user can start typing immediately. This makes the page more usable.
Now to do the computation. Here’s some JS (warning: there’s a bug):
$(document).ready(function() {
$("#meal_cost").focus();
$("#compute_tip").click(function(){
//Get the cost of the meal.
meal_cost = $("#meal_cost").val();
//Compute the tip and total.
tip = meal_cost * 0.15;
total_cost = meal_cost + tip;
//Output the results.
$("#tip").text(tip);
$("#total_cost").text(total_cost);
});
});
Figure 3. Tip computer JS (broken)
Please try the code.
Line 5 gets whatever the user types into the input field and puts it into the variable meal_cost.
Line 7 works out the tip amount. * means “multiply,” so the line reads:
Take the contents of the variable
meal_cost, multiply it by 0.15, and put the result in the variabletip.
Line 8 takes the contents of the variable meal_cost, and adds the contents of the variable tip, putting the result into the variable total_cost. At least, that’s what the intent is.
Lines 10 and 11 show the results.
When I try the page, it works, partially. I type in 30 for the meal cost, click the button, and get this:

Figure 4. Broken tip computer
What!? The tip is fine. 30 × 0.15 is 4.5. But the page says that 30 + 4.5 is 304.5! It should be 34.5! What the !##@! is going on?
Welcome to the Wonderful World of Bugs.
The problem is that + has two meanings in JavaScript. The meanings are:
Earlier, we say code like this:
"Hello " + user_name + "!"
There’s that +. It meant:
Take the text “Hello “, append the contents of the variable
user_name, and append the text “!”.
That’s what this line in Figure 3 is doing:
total_cost = meal_cost + tip;
JavaScript treats the contents of the variables mean_cost and tip as text rather than numbers. It’s taking the contents of the variable mean_cost, and appending the contents of the variable tip. So:
30 + 4.5 gives 304.5
This is stupid. Really stupid. That’s what computers are. Very, very, very stupid.
We want to tell JavaScript: “Dude, treat the contents of the variables mean_cost and tip as numbers.” Then it will add instead of appending.
You should always address a JavaScript program as “dude.”
Change the code to:
total_cost = parseFloat(meal_cost) + parseFloat(tip);
In computerese, a “float” is a kind of number. There are many kinds of numbers. For instance, an integer is a whole number. A float is a number that can have a fraction. The function parseFloat() tells JS to treat the stuff inside the () as a number that can have a fraction.
When you do this, the + becomes an add. Try it.
Change the program so it only tips 12%. Think anyone will notice?
(Log in to enter your solution to this exercise.)
Write a page that will convert kilograms to pounds. There are 2.2 lbs per kilo. The page will look like this to start with:

Figure 1. Page at start
The user types a number in and clicks the button:

Figure 2. Output
Upload your solution to your server, and put the URL below.
(Log in to enter your solution to this exercise.)
Let’s change the program so that the bill is split evenly between more than one person. Please try this version.
Here’s the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Tip</title>
<script type="text/javascript">
$(document).ready(function() {
$("#meal_cost").focus();
$("#compute_tip").click(function(){
//Get the cost of the meal.
meal_cost = $("#meal_cost").val();
//Get the number of diners.
humans = $("#humans").val();
//Compute the tip and totals.
tip = meal_cost * 0.15;
total_cost = parseFloat(meal_cost) + parseFloat(tip);
cost_per_human = total_cost / humans;
//Output the results.
$("#tip").text(tip);
$("#total_cost").text(total_cost);
$("#cost_per_human").text(cost_per_human);
});
});
</script>
</head>
<body>
<h1>Tip Computer</h1>
<p>
Meal cost:
<input type="text" id="meal_cost">
</p>
<p>
Number of humans:
<input type="text" id="humans">
</p>
<p>
<button type="button" id="compute_tip">Compute</button>
</p>
<p>Tip: <span id="tip"></span></p>
<p>Total: <span id="total_cost"></span></p>
<p>Cost per human: <span id="cost_per_human"></span></p>
</body>
</html>
Figure 5. Group tip computer
There’s a new input field (line 35). The code is roughly the same. The total cost is divided up in line 18. There isn’t a parseFloat() in line 18, because the / operator only means “division.” So while + has two meanings, / only has one.
Write a page that will convert kilograms and grams to pounds. There are 1,000 grams per kilo, and 2.2 lbs per kilo.
The page will look like this to start with:

Figure 1. Page at start
The user types numbers and clicks the button:

Figure 2. Output
Hint: Use at least one parseFloat().
Upload your solution to your server, and put the URL below.
(Log in to enter your solution to this exercise.)
When the page first loads, the output area looks a little strange. Just the headings, with no numbers.
It would be better if we could hide the output area at first, and show it after the user has entered the data and clicked the button.
The Camtasia Studio video content presented here requires a more recent version of the Adobe Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.
Figure 6. Improving the interface
Let’s see how to do that. Please try the page.
We’ll change the HTML to this:
<div id="output_area"> <p>Tip: <span id="tip"></span></p> <p>Total: <span id="total_cost"></span></p> <p>Cost per human: <span id="cost_per_human"></span></p> </div>
Figure 7. Wrapping in a <div>
The output tags are wrapped in a new tag, <div>. Use <div> when you want to make a container, as we’ve done here. A container is a tag that has a bunch of other tags inside it.
If we do something to the <div>, we do something to all its contents as well. So, if we hide the <div>, we hide all of its contents. If we show the <div>, we show all its contents.
Here’s what we want to do:
<div>.<div>.Here’s the JavaScript for the page:
$(document).ready(function() {
$("#output_area").hide();
$("#meal_cost").focus();
$("#compute_tip").click(function(){
...
//Output the results.
$("#tip").text(tip);
$("#total_cost").text(total_cost);
$("#cost_per_human").text(cost_per_human);
//Show the output
$("#output_area").show();
});
});
Figure 8. New JavaScript
I gave the <div> an id of output_area. We can use that in the code to identify the thing to hide and show.
This line…
$("#output_area").hide();
...hides the <div>, including everything inside it. The line is inside $(document).ready(), so it runs when the page is loaded.
This line…
$("#output_area").show();
...shows the <div>, including everything inside it. The line is run after the output values are inserted into total_cost and cost_per_human.
W00f!
Let’s add some animation to the way the output area appears. You can try it.
The Camtasia Studio video content presented here requires a more recent version of the Adobe Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.
Figure 9. A little animation
Pass a value to the show() function:
$("#output_area").show('medium');
That’s it! Change the speed by giving show() different values, like 'fast', 'slow', and 3000. The last one extends the effect over 3,000 milliseconds (3 seconds).
Write a page that will convert kilograms and grams to pounds. There are 1,000 grams per kilo, and 2.2 lbs per kilo.
The page will look like this to start with:

Figure 1. Page at start
No output area is shown.
The user types numbers and clicks the button:

Figure 2. Output
The output appears with an animated effect.
Hint: Use at least one parseFloat().
Upload your solution to your server, and put the URL below.
(Log in to enter your solution to this exercise.)
You learned:
text().What happens when you make a mistake in your code? Time to talk about debugging.
You’re learning how to do some basic stuff with JavaScript. But what happens when your code doesn’t work?
Learn:
alrt(). alert() statements to track program execution. If alert() messages are supposed to show up, but don’t, you know what code is not executing.alert() statements to look at the values of variables.There are two types of errors:
The first type is easier to find and fix.
Syntax errors are when the browser can’t understand your instructions. For example, suppose a human asks you to:
Grag the blint flakengargle.
The words don’t make any sense.
Here’s a JavaScript example. Suppose you put this on a page:
alrt('Dogs are great!');
The browser won’t understand alrt. You meant this:
alert('Dogs are great!');
Most syntax errors are simple typing errors, like this one.
Up to now, you may have been using Notepad++. It’s a good editor to start with. Easy to use. It works just fine.
But it’s time to move on.
Install Netbeans, an integrated development environment (IDE). An IDE is a collection of tools to help people write code. The tools include an editor that, get this, checks for errors!
Here’s some code in Notepad++.

Figure 1. Code in Notepad++
Looks OK. Here’s the same code in Netbeans.

Figure 2. Code in Netbeans
Netbeans can analyze your code, and flag errors. This will save you a lot of time and frustration.
So, go to netbeans.org. Download the PHP bundle, and install it. Remember, the PHP bundle.
Netbeans is fairly easy to use, but there’s one hitch in getting started. Netbeans has the concept of projects, a collection of related files. You need to set up projects to work with Netbeans.
Don’t worry. It’s easy. Suppose you’ve been working on CoreDogs exercises. You created this in your Documents directory:

Figure 3. Your directories
You’ve been putting your CoreDogs files in the CoreDogs directory:

Figure 4. Files in your directories
You’ve been using Notepad++ to work on these files.
All you have to do is tell Netbeans to put your files into a project, and you’re ready to go. Let’s see how.
Here’s Netbeans without any projects.

Figure 5. Netbeans, empty
Create a new project.

Figure 6. New project
You’ll see a screen like this:

Figure 7. New project form
Tell it that you want to create a PHP project from existing sources:

Figure 8. Create a PHP project from existing sources
Er, you installed the Netbeans PHP bundle, right?
PHP is a language for programs that run on Web servers. It’s covered in CoreDogs, in the ServerCore book.
The next Netbeans form is like this:

Figure 9. Name and location form
Select the directory you’ve been using for your exercises:

Figure 10. Select your directory
Click the Finish button. Netbeans will create your project.
Open the Sources, and you’ll see your files:

Figure 11. Your files in Netbeans
Double-click on a file to open it. Right click to create a new file:

Figure 12. Creating a new file
If you look at your directory in Windows Explorer, you’ll see that Netbeans added a new subdirectory:

Figure 13. Netbeans project subdirectory
Don’t delete it, or you’ll have to make the project again.
So, now you’re running Netbeans. There are other good IDEs, like Aptana.
These IDEs are good, but they’re not perfect. For example, check the code in Figure 2. There’s an error in the JavaScript that Netbeans didn’t flag as an error. The yellow in line 11 says that Netbeans thinks there might be something funny going on, but there’s no error icon.
You’ll need other tools to squash those bugs.
When a browser finds a syntax error in your JavaScript, it will do two things:
If you can find the error message, you can fix the error. But the browser won’t show an error message in the middle of a Web page. You have to know where to look.
Different browsers show errors in different places. Let’s talk about Firefox, CoreDog’s official browser. Firefox is better at helping you find syntax errors than Internet Explorer. You’ll find that Firefox is a better choice for Web work. If you haven’t already, download Firefox and start using it.
Firefox shows errors in its error console. The error console collects all the error messages from all the pages Firefox shows.
Open the error console from the Tools menu:

Figure 14. Opening the error console
Try it now. Your menu will look different, depending on the add-ons you have installed.
Here’s what I saw when I opened my error console just now:

Figure 15. The error console
Yikes!
Don’t panic. It’s normal to have a bunch of stuff showing.
You want to start with a clean slate, so you see error messages from your code, and not from other people’s pages. Click the Clear button. This erases all the messages.
OK. Now let’s load a page with an error, and see what happens. Here’s the code you’ll try to run:
$(document).ready(function() {
alert("About to try a broken line of JavaScript.");
alrt("This line is broken");
alert("Just tried to run a broken line.");
});
Figure 16. Broken JavaScript
To try it, click on this link.
Now check the error console. This is what I see:

Figure 17. Error message
Sometimes it’s hard to know what an error message means. The browser doesn’t say, “Hey! You typed alert wrong.” Because it doesn’t know that. Maybe you really meant to type alrt, but forgot to tell the browser what alrt means. So you might have to think a bit to figure out what the problem is.
You can Google error messages, if you want. For example, you could search for:
javascript error “is not defined”
When I tried the page, I saw an alert box for “About to try a broken line of JavaScript.” But I didn’t see one for “Just tried to run a broken line.” This line looks right to me:
alert("Just tried to run a broken line.");
The line is right. But the browser stops as soon as it finds a syntax error. So it never gets to that line.
The error message we just saw showed up as soon as the page was loaded. Why? Because the bad line was in the $(document).ready() event. Code there runs when the page loads.
Sometimes errors might not appear until later. Let’s try this one:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Broken again</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#button_of_doom").click(function(){
alert("About to try a broken line of JavaScript.");
alrt("This line is broken");
alert("Just tried to run a broken line.");
});
});
</script>
</head>
<body>
<p>Click the button to make an error message.</p>
<p>
<button type="button" id="button_of_doom">Doom</button>
</p>
</body>
</html>
Figure 18. More broken JavaScript
The broken JS is line 11. This time, it’s inside the $("#button_of_doom").click() event. The browser won’t try to run line 11 until the button is clicked.
Let’s give it a try. First, clear the error console. Now click this link to load the page.
Check the error console. It should be empty. The browser hasn’t tried to run the bad line yet.
Click the button, and then the OK button on the dialog box that appears. Now check the error console again. There’s the error message.
So, if your JavaScript program isn’t running:
Most syntax errors are simple typing errors. They’re easy to fix. But there’s another type of error: a logic error. Logic errors are usually more difficult.
Wow, finding bugs might be hard. Programming could get irritating.
Frustration is normal when doing computer work. You need ways of handling it. Know how to:
Or you could be like this guy.
The error console will help you fix syntax errors. Let’s move on to the second type of bug.
Logic bugs are where the browser understands what you have told it, but you’ve told it the wrong thing. Sometimes these are just typing mistakes, but usually they’re thinking mistakes.
A problem with logic errors is that the browser won’t show an error message. The error console won’t help. You have to track down the error on your own.
Here’s a page with a simple logic error. You can try the page.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Square a Number</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#input_number").focus();
$("compute_button").click(function() {
input_number = $("#input_number").val();
square = input_number * input_number;
$("#square").text(square);
});
});
</script>
</head>
<body>
<h1>Square a Number</h1>
<p>
Type in a number, and I will tell you its square. For example,
the square of 3 is 3 x 3 = 9.
</p>
<p>
Number:
<input type="input" id="input_number">
<button type="button" id="compute_button">Compute</button>
</p>
<p>Square <span id="square"></span></p>
</body>
</html>
Figure 19. Another broken page
See if you can find the problem by just looking through the code.
Don’t worry if you can’t spot the error. It’s easy to overlook, no matter how much you stare at the code.
alert()One way to find errors is to add alert() statements, like this:
<script type="text/javascript">
alert("Before the ready function");
$(document).ready(function() {
alert("Starting the ready function");
$("#input_number").focus();
$("compute_button").click(function() {
alert("Starting the click function");
input_number = $("#input_number").val();
square = input_number * input_number;
$("#square").text(square);
alert("Ending the click function");
});
alert("Ending the ready function");
});
</script>
Figure 20. Adding alert()s
I know when the alert dialogs should appear. I can run the page, and see whether what I expect to happen does happen. If it doesn’t, this will help me find the mistake.
Here’s when each alert dialog should appear:
The Camtasia Studio video content presented here requires a more recent version of the Adobe Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.
Figure 21. Tracking down the problem
You can try the page.
OK, so the page shows the alerts for lines 8, 10, and 19, but not for lines 13 or 19. Line 13 should show a message when the user clicks the compute button. Maybe the code for the compute button is not being run.
Here’s the code that sets up the click event for the button:
$("compute_button").click(function() {
Aha! I see the problem now. Do you see it?
Compare this line to the corresponding line from an example in the last lesson.
$("#compute_tip").click(function(){
I missed the #! The code should be:
$("#compute_button").click(function() {
Without the #, the browser can’t find the button to tie the event code to.
Wow, all that trouble because of one missing character?
Yes. That’s quite normal in computer work. You need to be careful and patient.
You can try the fixed verion.
So, adding alert statements let us follow the execution of the JS. When we got something we didn’t expect, we were able to find the problem.
Sometimes that’s not enough. Here’s another version of the JS, with a different problem from the last one.
<script type="text/javascript">
$(document).ready(function() {
$("#input_number").focus();
$("#compute_button").click(function() {
input_number = $("#input_number").val();
square = input_number + input_number;
$("#square").text(square);
});
});
</script>
Figure 22. A different problem
Try the page. You get output this time, but it’s wrong:

Figure 23. Wrong output
If I add the same alert()s we had last time, I’ll find that everything appears just fine. All of the code is executing. But the output is wrong.
Hmm. Maybe I’ll check that the data is being read correctly, and the computations are done right.
I’ll add some more alerts:
<script type="text/javascript">
$(document).ready(function() {
$("#input_number").focus();
$("#compute_button").click(function() {
alert("Starting the click function");
input_number = $("#input_number").val();
alert("input_number:" + input_number);
square = input_number + input_number;
alert("square:" + square);
$("#square").text(square);
alert("Ending the click function");
});
});
</script>
Figure 24. alerts
Look at lines 12 and 13:
input_number = $("#input_number").val();
alert("input_number:" + input_number);
The alert() shows the value of a variable. I can compare it with what it should be.
Let’s run the code.
The Camtasia Studio video content presented here requires a more recent version of the Adobe Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.
Figure 25. Showing variable values
You can try the page.
So, we know that this line is causing the problem:
square = input_number + input_number;
Aha! The + should be *! Change it, and the page will work.
W00f!
Fix the bugs in this page.
Upload your solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
Debugging takes time. Inserting alert statements, loading pages, etc.
A suggestion. Before you test your page for the first time, read over the code. Carefully. Take your time. You can find mistakes without having to use alerts.
Firebug is a debugging add-on for Firefox.
alrt(). alert() statements to track program execution. If alert messages are supposed to show up, but don’t, you know what code is not executing.alert() statements to look at the values of variables.You know how to grab data from text fields, and do things with them. But what if the user doesn’t type anything? Or says that his or her age is, say, -15?
You’ve learned how to make pages that interact with the user. Renata and CC have been learning right along with you. Let’s see how they use their skills to make a page.

The dead have risen. Millions of them.
It’s just humans, of course. We dogs know better than to become zombies.
Your pack starts living in caves, going out for food as needed (MacDonalds and Burger King survived the apocalypse. Hmmm…). Wandering human zombies attack your foraging expeditions. Some of you hold each zombie down, and the rest chew its head off. Nasty, but it works.
There are three types of zombies: regular, wrestler, and geek. Wrestler zombies were professional wrestlers when they were alive. They’re tougher than regular zombies.
Geek humans became the toughest zombies of all. They’re hard to take down. You have to be very careful with geeks. Maybe because of their… say it with me… braaains.
You keep track of the zombies you rekill each day, and compute an overall daily score. You get one point for each regular zombie, five for a wrestler, and ten for a geek.
Write a Web page that lets the user enter the number of each type of zombie, and computes the total score.
Let me show you what your page should do.
You can try my solution.
OK, you two give it a try.
I guess that’s us.
Yep.
Well, we should, er… I don’t know how to get started.
Hmmm… Hey, how about we break the task up into pieces?
Makes sense. What’s the first piece?
Let’s start with what’s easy to do. The HTML isn’t complicated. Some text, a few fields. How about we do that first?
OK, good idea. When I create a new page, the first thing I do is copy the template we learned at the very beginning of ClientCore.
Works for me. I’ll make a new file in Netbeans and paste the HTML in.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>TITLE</title>
</head>
<body>
BODY
</body>
</html>
CC and Renata start with something they know works. They cut-and-paste from the HTML page template pattern.
OK, good. Now let’s add some HTML. Just a little to begin with.
[Type type]
Here it is.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Zombie Score</title>
</head>
<body>
<h1>Zombie Score</h1>
</body>
</html>
How’s that look in the browser?
Let’s see. I’ll open the file so far.
OK! Something showed up! W00f!
Yes! How about we do some CSS?
OK. Let’s do the background color.
Yes, but we need a color code. Hey, Kieran!
What’s up?
Can you give us the color code for the background?
Sure. Let me look at the source… OK, it’s FFFFEE.
Now we need to add this:
background-color: #FFFFEE;
You need to put that in the HTML CSS tag.
Oh, yes, that’s right. And does it get applied to the <body>?
Let me look at an example on CoreDogs… OK, you’re right.
Here’s the new page.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Zombie Score</title>
<style type="text/css">
body {
background-color: #FFFFEE;
}
</style>
</head>
<body>
<h1>Zombie Score</h1>
</body>
</html>
Let’s have a look.
Cool!
CC and Renata take one small step at a time, and check their work as they go. This is easier than trying to create the entire page at once.
Hey, can I type in the font CSS?
Huh?
This is what we want it to look like:

This is what it looks like now:

Oh, yes. Let’s take a look at that basic text styling pattern.
Why reinvent the wheel? Patterns make things easier.
Good idea. Hmm, let’s use Verdana. I like that. And text that’s 14 pixels. Makes it big enough to read. How’s this?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Zombie Score</title>
<style type="text/css">
body {
background-color: #FFFFEE;
font-family: Verdana, sans-serif;
font-size: 14px;
}
</style>
</head>
<body>
<h1>Zombie Score</h1>
</body>
</html>
What’s the sans-serif on line 9 for?
If the computer doesn’t have the Verdana font, the browser will show a generic sans serif font.
Oh, yes, I remember that now. How’s it look?
Let’s check it out.
Nice! How about the instructions, you know, that say “Please enter the number” and so on.
Here we go. I’ll add the first field, as well. [Type type typity]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Zombie Score</title>
<style type="text/css">
body {
background-color: #FFFFEE;
font-family: Verdana, sans-serif;
font-size: 14px;
}
</style>
</head>
<body>
<h1>Zombie Score</h1>
<p>Please enter the number of each type of zombie you
rekilled today. Then click the Compute button.</p>
<p>Regular:<br>
<input type="text">
</p>
</body>
</html>
Hmmm. Is there something missing in the <input> on line 19?
What?
Let me look at CoreDogs… OK, you might need an id.
Why would we… Oh, OK, I remember. We need to give the <input> field an id, so when we get to the JavaScript, we can refer to the field. How about this?
<input type="text" id="regular">
That’s better. Let’s try it.
W00f! W00f!
Looking good! I’ll add the other input fields, and the button.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Zombie Score</title>
<style type="text/css">
body {
background-color: #FFFFEE;
font-family: Verdana, sans-serif;
font-size: 14px;
}
</style>
</head>
<body>
<h1>Zombie Score</h1>
<p>Please enter the number of each type of zombie you
rekilled today. Then click the Compute button.</p>
<p>Regular:<br>
<input type="text" id="regular">
</p>
<p>Wrestler:<br>
<input type="text" id="wrestler">
</p>
<p>Geek:<br>
<input type="text" id="geek">
</p>
<p>
<button type="button" id="compute">Compute</button>
</p>
</body>
</html>
So how do we do it? I’m stuck.
Let’s trying breaking it down into pieces again, like we did with the HTML.
OK, we need to get the cursor in the first field when the program loads. Was there a pattern for that?
Let me check… You’re right, there is a pattern we can use. Let me copy the code and paste it in. Oh, and I need to make it put the cursor in the first input field.
Patterns to the rescue! Again!
[Type type type type]
Hey, wait a minute. Look at that code in Netbeans.

Oh. That marker means Netbeans has found a problem, right?
Yes. It’s on the ). Maybe the opening ( is missing.
No, it’s there.
Ooo! Look! There’s a {, but no } later!

You’re right! Add it, er, before the ).
Before it?
Yes, the ( is opened first, and then the {. Close the } first, and then the ). So they nest correctly.
Oh, I get it. [Type type]

W00f! That was it!
Smart editors like Netbeans find some errors for you. This will save you time. And frustration.
OK. Here’s all the code so far.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Zombie Score</title>
<style type="text/css">
body {
background-color: #FFFFEE;
font-family: Verdana, sans-serif;
font-size: 14px;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("#regular").focus();
});
</script>
</head>
<body>
<h1>Zombie Score</h1>
<p>Please enter the number of each type of zombie you
rekilled today. Then click the Compute button.</p>
<p>Regular:<br>
<input type="text" id="regular">
</p>
<p>Wrestler:<br>
<input type="text" id="wrestler">
</p>
<p>Geek:<br>
<input type="text" id="geek">
</p>
<p>
<button type="button" id="compute">Compute</button>
</p>
</body>
</html>
Let’s give it a try.
Er, the cursor isn’t in the first field. Why didn’t it work?
I don’t know. What do we do now?
Let’s look through the code again.
(Five minutes pass…)
I didn’t see anything wrong.
Me neither. Hey, let’s look at the error console. You know, that we learned about in the debugging lesson?
OK. I’ll bring it up.

Look, right at the bottom. “$ is not defined.” We’ve used $ before. Why is it breaking now?
(Sigh) I don’t know. Let’s ask the pack leader. Er, Kieran?
What’s up?
What’s the error message “$ is not defined” mean?
Oh, that one. You know the HTML page template pattern?
Yes.
Look at the section on JavaScript and jQuery. See if there’s anything missing on your page.
OK. Let’s take a look at the pattern …
Oh! There! We forgot the line that loads jQuery!
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
I’ll cut-and-paste it. [Click click type type]. OK, now let’s see what we have.
Use the error console to see if the browser found errors in your code. If you see the error “$ is not defined” in the error console, make sure you have loaded jQuery.
W00f! W00f! W00f!
Check that you are using the right pattern for the situation. CC and Renata should have started with the “Web page with JavaScript and jQuery” pattern, not just the “Web page” pattern.
Now what?
I’m not sure. Hmmm… Let’s look at the pattern list. Maybe we’ll see something useful.
Here’s one, Run code on click. We want to do something when the button is clicked.
OK. Let’s take a look… Oh, OK. I’ll change the code.
<script type="text/javascript">
$(document).ready(function() {
$("#regular").focus();
$("compute").click(function() {
});
});
</script>
How will we know whether it worked?
Hmmm. Oh, look at this in the pattern. An alert. We can do that. I’ll change it to:
<script type="text/javascript">
$(document).ready(function() {
$("#regular").focus();
$("compute").click(function() {
alert('Clicked');
});
});
</script>
So we should see the message “Clicked” when we click on the button.
Great! Let’s give it a try.
Oh, come on, you stupid machine! Why didn’t you work?
Check the error console.
OK… Nothing new.
(Sigh) Let me eyeball the code… Hey! It might be this. Look at the these two lines:
$("#regular").focus();
$("compute").click(function() {
I see them. So what?
We forgot the # in front of compute.
ACK! You’re right. The # means “look for an something with an id of compute.” Without it, jQuery won’t find the button.
This is a common mistake.
I’ll put it in:
$("#regular").focus();
$("#compute").click(function() {
Now let’s try it.
W00f! W00f! W00f! W00f!
W00f! W00f!
Now what?
OK, the user presses the button. What should our page do?
Let’s think it through. At the end, we want to show the total score. One point for regular zombies, five for wrestlers, and ten for geeks. Something like this:
score = regular + wrestlers x 5 + geeks x 10
Oh, OK. Let me try something. When the user clicks the button, the code should do this:
Get numbers from the fields (what the user typed).
Compute the score.
Show the score.
Yes, that’s it. That’s looks like the Input-process-output pattern. Get the input, do something with it, and show the output.
Alright, we’re getting somewhere. Let’s get the three numbers. Here’s what we have so far:
<script type="text/javascript">
$(document).ready(function() {
$("#regular").focus();
$("compute").click(function() {
alert('Clicked');
});
});
</script>
Let’s start by getting rid of that alert.
Wait a minute, I’ve got an idea. Leave it in there. Let’s get whatever the user typed into the first input field, and use the alert to show it.
Smart Renata! One small step at a time. Then check that it works.
Here, you take the keyboard. It’s fortunate we have a keyboard that’s good for dogs. Have you seen the tiny keys on the humans’ keyboards? Nasty.
Let’s see. How about this?
<script type="text/javascript">
$(document).ready(function() {
$("#regular").focus();
$("compute").click(function() {
regular = $("regular").val();
alert(regular);
});
});
</script>
You forgot the # in line 5.
Oh, yes. Here.
<script type="text/javascript">
$(document).ready(function() {
$("#regular").focus();
$("compute").click(function() {
regular = $("#regular").val();
alert(regular);
});
});
</script>
Let’s try it.
W00f! It worked!
Now do the other two fields.
OK! [Type type type type]
<script type="text/javascript">
$(document).ready(function() {
$("#regular").focus();
$("compute").click(function() {
regular = $("#regular").val();
alert(regular);
wrestler = $("#wrestler").val();
alert(wrestler);
geek = $("#geek").val();
alert(geek);
});
});
</script>
Let’s try it.
Yes! W00f! W0000f! Resistance is futile, computer!
W00f!
Let’s go back to the three steps.
Get numbers from the fields (what the user typed).
Compute the score.
Show the score.
We’ve done the first one. Now for the second. Compute the score. [Type type]
<script type="text/javascript">
$(document).ready(function() {
$("#regular").focus();
$("compute").click(function() {
regular = $("#regular").val();
alert(regular);
wrestler = $("#wrestler").val();
alert(wrestler);
geek = $("#geek").val();
alert(geek);
score = regular + 5 * wrestler + 10 * geek;
alert(score);
});
});
</script>
How’s it look?
Great! Let’s give it a try. I’ll type 1, 2, and 3 in the fields.

You’ve got to be kidding me.
A-R-G-H!!
(Depressed silence)
Hey, wait a minute. Didn’t we see something like this before? When JavaScript was getting the math wrong?
Hmmm, yes, we did. Wasn’t it just a couple of lessons ago?
Here it is! We need to tell JavaScript to treat what it gets from the input fields as numbers. With that parseFloat thing.
Oh, yes, that’s right! We need to put parseFloat() around everything we get from the user, at least everything that we want to be a number. But I’m not sure exactly what to type.
Me neither, but I’ve got something I want to try. [Type type type type type type]
<script type="text/javascript">
$(document).ready(function() {
$("#regular").focus();
$("compute").click(function() {
regular = $("#regular").val();
alert(regular);
wrestler = $("#wrestler").val();
alert(wrestler);
geek = $("#geek").val();
alert(geek);
score = parseFloat(regular) + 5 * parseFloat(wrestler) + 10 * parseFloat(geek);
alert(score);
});
});
</script>
Do you need all three of those parseFloats on line 11?
I don’t know. But let’s give it a try. I’ll type 1, 2, and 3 in the fields again.
W00f! W00f! W00f! W00f! W00f!
We’ve got it! Now we have the first two parts of:
Get numbers from the fields (what the user typed).
Compute the score.
Show the score.
We’ve done the last one, too. We’ve shown the score.
Not in the right way. Look at the movie again.
Oh, yes. We need to put the score on the page, and show it. Let’s see if there’s a pattern for that.
How about this one? Change text on the page.
Looks good. First we need the output area.
Let’s do this. I’ll remove the alerts, too. [Type type]
$("#compute").click(function(){
regular = $("#regular").val();
wrestler = $("#wrestler").val();
geek = $("#geek").val();
score = parseFloat(regular) + 5 * parseFloat(wrestler) + 10 * parseFloat(geek);
$("#score").text(score);
});
...
<p>
<button type="button" id="compute">Compute</button>
</p>
<p>
Score: <span id="score"></span>
</p>
Let’s try it.
W00f! W00f! We’re almost done. I found this pattern that hides output areas until they’re needed. Give me that keyboard. [Type type type type type]
$(document).ready(function() {
$("#output_area").hide();
$("#regular").focus();
$("#compute").click(function() {
regular = $("#regular").val();
wrestler = $("#wrestler").val();
geek = $("#geek").val();
score = parseFloat(regular) + 5 * parseFloat(wrestler) + 10 * parseFloat(geek);
$("#score").text(score);
$("#output_area").show('fast');
});
});
...
<p>
<button type="button" id="compute">Compute</button>
</p>
<p id="output_area">
Score: <span id="score"></span>
</p>
On line 18, I gave the output area an id. Then when the page loads, line 2 hides the entire output area.
The score is computed, and put into the output on line 9. Then line 10 shows the entire output area.
Now, for the big test!
It worked! W00f! W00f! W00f!
W00f! W00f! W00f! W00f! W00f!
How’s it going?
We got it! W00f! W00f!
Good job! W00f!
Coffee time?
And a nice dog biscuit. Let’s go!
Renata and CC created a page. They started with a template they knew worked. Then they went step by baby step, adding something and then checking that it worked. They used the alert statement to help.
Renata and CC used patterns a lot. They went back to the pattern library again and again.
They used Netbeans, a smart editor. It marked errors it found.
You should use the same habits in your own work.
Let’s see how you can add a quiz about yourself to your eMe.
You know quite a lot now. You know some events, and how to do things when the events fire. Let’s put that knowledge to use on your eMe site.
Make a quiz, with at least five questions. You can try mine (though it has fewer questions).
Make a quiz about something on your interesting stuff list. If you can’t think of anything, make a quiz about yourself. Where you were born, when, like that.
The quiz will be based on the one we did earlier. It looked like this:

Figure 1. Earlier quiz
Here are the important bits from the code:
<script type="text/javascript">
$(document).ready(function() {
$(".right").click(function() {
$("#result").text("Right! W00f!");
});
$(".wrong").click(function() {
$("#result").text("Sorry, that's wrong.");
});
});
</script>
...
<p>What is 4 x 7?</p>
<p>Please click on the right answer.</p>
<p class="wrong">a. 14</p>
<p class="wrong">b. 47</p>
<p class="right">c. 28</p>
<p class="wrong">d. I will never need to know.</p>
<p id="result"></p>
Figure 2. Quiz starting code
Look at the HTML. In lines 14 to 17, each response is given a class of right or wrong. Line 18 is where we show the result of a click, that is, the “You’re right” or “You’re wrong” message. It has an id of result.
Line 4 shows what happens when the user clicks on the right answer (that is, something with the class of right):
$("#result").text("Right! W00f!");
This says:
Find the element with an
idofresult, and put the text “Right! W00f!” in it.
In the new quiz, we have more than one question. That means more than one set of answers, and more than one result area.

Figure 3. Quiz
There are two questions in Figure 3. Each one has its own set of answers, and result area.
When the user clicks an answer, the page should change only the matching result area.

Figure 4. Separate events
There are many ways to do this. We’ll talk about one that’s easy to understand.
We have to be able to refer to each result area separately. So we’ll give each one a different id. We also need to separate the answers for each question, so we can’t use just two classes, right and wrong. Instead, we’ll create separate right and wrong classes for each question.
Here’s the HTML we’ll use.
<h2>Q 1. When was I born?</h2> <p class="q1_right">a. 1960</p> <p class="q1_wrong">b. 1975</p> <p class="q1_wrong">c. 1985</p> <p class="q1_wrong">d. I was hatched, not born.</p> <p id="q1_result" class="result"></p> <h2>Q 2. What was the first programming language I learned?</h2> <p class="q2_wrong">a. Java</p> <p class="q2_wrong">b. JavaScript</p> <p class="q2_wrong">c. C</p> <p class="q2_right">d. FORTRAN</p> <p id="q2_result" class="result"></p> <h2>Q 3. What is the hex opcode for the Halt instruction on a Z80?</h2> <p class="q3_wrong">a. CD</p> <p class="q3_wrong">b. C9</p> <p class="q3_right">c. 76</p> <p class="q3_wrong">d. 20</p> <p id="q3_result" class="result"></p>
Figure 5. HTML for multi-question quiz
Have a look at the result sections, in lines 6, 13, and 20:
<p id="q1_result" class="result"></p>
<p id="q2_result" class="result"></p>
<p id="q3_result" class="result"></p>
Each one has a different id. But we want to style them all the same way, so we give them the same class.
Here’s the code for one of the questions:
<h2>Q 1. When was I born?</h2> <p class="q1_right">a. 1960</p> <p class="q1_wrong">b. 1975</p> <p class="q1_wrong">c. 1985</p> <p class="q1_wrong">d. I was hatched, not born.</p> <p id="q1_result" class="result"></p>
Figure 6. HTML for one question
Click on an item with a class of q1_right or q1_wrong, and the text of q1_result should change.
The other questions follow the same pattern:
<h2>Q 2. What was the first programming language I learned?</h2> <p class="q2_wrong">a. Java</p> <p class="q2_wrong">b. JavaScript</p> <p class="q2_wrong">c. C</p> <p class="q2_right">d. FORTRAN</p> <p id="q2_result" class="result"></p>
Figure 7. HTML for the another question
Click on an item with a class of q2_right or q2_wrong, and the text of q2_result should change.
Here’s the JavaScript:
$(document).ready(function() {
$(".q1_right").click(function() {
$("#q1_result").text("Right! I was born in 1960.");
});
$(".q1_wrong").click(function() {
$("#q1_result").text("Sorry, that's not it.");
});
$(".q2_right").click(function() {
$("#q2_result").text("Right! The first programming language I learned was FORTRAN.");
});
$(".q2_wrong").click(function() {
$("#q2_result").text("Sorry, that's not it.");
});
$(".q3_right").click(function() {
$("#q3_result").text("Right! The Halt instruction on a Z80 is 76 hex.");
});
$(".q3_wrong").click(function() {
$("#q3_result").text("Sorry, that's not it.");
});
});
Figure 8. Quiz code
The first event handler is:
$(".q1_right").click(function() {
$("#q1_result").text("Right! I was born in 1960.");
});
So, clicking on something with a class of q1_right changes the text in q1_result. Notice that it’s $(".q1_right") and not $("#q1_right"). Use a . for a class, and a # for an id.
Let’s make an exercise for all this.
Make a quiz, with at least five questions.
Use the same styles you created for the text pages with external styles exercise. (You can copy the entire .css file, if you want).
Upload your solution to your server. Put the result below.
(Log in to enter your solution to this exercise.)
In this lesson, you created an interactive quiz. How cool is that? You are mastering some cool skills.
Users often make mistakes when they type data into forms. Like giving their year of birth as 1880, instead of 1980. Let’s see how you handle errors like that.
You know how to grab data from text fields, and do things with it. But what if the user doesn’t type anything? Or says that his or her age is -15?
This lesson is about validation, that is, checking the data that the user typed.
By the end of this lesson, you should:
Let’s start with this page:

Figure 1. Age
If the user clicks the button without entering anything, this is what happens:

Figure 2. Age is empty
Here’s the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Check age 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
body {
font-family: Verdana, sans-serif;
font-size: 14px;
background-color: #FFFFE0;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#age").focus();
$("#go").click(function(){
age = $("#age").val();
if ( age == "" ) {
alert("Please enter your age.");
}
});
});
</script>
</head>
<body>
<h1>Check age 1</h1>
<p>
Age:
<input type="text" id="age" size="3">
</p>
<p>
<button type="button" id="go">Go</button>
</p>
</body>
</html>
Figure 3. Age checker
You can try it.
The action starts on line 18:
age = $("#age").val();
if ( age == "" ) {
alert("Please enter your age.");
}
Part of Figure 3. Age checker
Line 18 gets the value that the user typed, and puts it into the variable age.
The next line has an if statement. This is what does the check. The general form of an if statement is:
if (test) {
Do this if the test istrue.
}
The test is a comparison that is either true or false. Here’s line 19 again:
if ( age == "" ) {
== is true if the thing on the left is the same as the thing on the right. The thing on the left contains the value the user typed. The thing on the right is an empty string. The quotes are jammed together, with nothing between them.
Important! == and = are not the same! == means “are they the same?” = means “put something into a variable.” This would fail:
if ( age = "" ) { //WRONG!
Write a page that looks like this:

Figure 1. Favorite animal
If the user clicks the button without typing anything, show a message:

Figure 2. No favorite animal
Upload your solution to your server and put the URL below.
(Log in to enter your solution to this exercise.)
true code and false codeYou can also tell the browser what to do when the test is false:
if (test) {
Do this if the test istrue.
}
else {
Do this if the test isfalse.
}
Let’s use this in the age checker.
age = $("#age").val();
if ( age == "" ) {
alert("Please enter your age.");
}
else {
alert("Thank you!");
}
Figure 4. Age checker junior
Change your previous page so that it thanks the user if s/he puts something in the field. Like this:

Figure 1. Thank the user
Upload your solution and put the URL below.
(Log in to enter your solution to this exercise.)
You can include as many statements as you like between the braces of an if statement. For example, you could do this:
age = $("#age").val();
if ( age == "" ) {
alert("Please enter your age.");
}
else {
double_age = age*2;
alert("In " + age + " years, you will be " + double_age + ".");
alert("Last year, you were " + (age - 1) + ".");
}
Figure 5. Age checker III
You can try it.
Change your favorite animal page. If the user enters nothing, it shows two messages. The first one should be:

Figure 1. First message
When the user clicks the button, a second message shows:

Figure 2. Second message
(Log in to enter your solution to this exercise.)
if this and if thatOften you want to chain if statements together. Here’s an example.
age = $("#age").val();
if ( age == "" ) {
alert("Please enter your age.");
}
else if ( isNaN(age) ) {
alert("Please enter a number.");
}
else if ( age < 21 ) {
alert("Sorry, you are too young.");
}
else {
alert("Thank you!");
}
Figure 6. Yet another age checker
Just one of the alert()s above will be shown. You can try it.
There are some other new things here. Here’s line 22:
else if ( isNaN(age) ) {
isNaN(age) is true if age is Not A Number. You have to get the name right when you type the function. So isnan, IsNaN, and isNAN are all incorrect.
Here’s line 25:
else if ( age < 21 ) {
This is true if age is less than 21.
Here are some other comparisons you can do:
== |
is equal to |
!= |
is not equal to |
< |
is less than |
<= |
is less than or equal to |
> |
is greater than |
>= |
is greater than or equal to |
Figure 7. Comparison operators
You can check text strings as well. For example:
if ( age == "old" ) {
alert("You don't look old.");
}
Create a page that asks the user to answer a math question:

Figure 1. Math quiz
Show an alert() like this:

Figure 2. Math quiz response
Here are the rules for the alert()s:
Upload your solution to your server, and put the URL below.
(Log in to enter your solution to this exercise.)
You know how to grab data from text fields, and do things with it. But what if the user doesn’t type anything? Or says that his or her age is -15?
In this lesson, you learn how to:
Wow! That was one of the most complicated lessons so far. But you will use the things you’ve learned again and again.
You should do the four recommended exercises. Do the optional exercises if you want more practice.
Exercises in the Explore section are more challenging. You may need to use HTML and CSS that isn’t covered in CoreDogs. Get ready to Google!
The invert of a number is 1 divided by that number. So the invert of 2 is 1/2 = 0.5. The invert of 3 is 1/3 = 0.333. The invert of 82.8 is, er, something or other.
Write a program that inverts a number that the user enters.
Upload the solution to your server, and put the URL below.
(Log in to enter your solution to this exercise.)
Write a JavaScript program to compute the length of the hypotenuse of a right triangle from the length of the other two sides.
The formula is:
hyp = Math.sqrt(c1*c1 + c2*c2);

(Image from Wikipedia)
Upload your solution to your server, and paste the URL below.
(Log in to enter your solution to this exercise.)
Paula is an accountant clown. No, really. Companies hire her to do her shtick at board meetings. You can just imagine how funny it is. You’ll have to, because I can’t bear to describe it.
Paula has a pay-by-performance policy. The more laughs she gets, the more she gets paid. She charges:
For example, suppose there were 20 people at a board meeting. Paula does her act. On average, each person guffawed 8 times, and had 5 belly laughs. So:
Revenue per person = 0.80 × 8 + 1.10 × 5 = $11.90
Total revenue = $11.90 × 20 = $238
Paula has a hard time with numbers. Write a Web page to help her estimate how much she will earn for a gig.
The page starts off like this:

Figure 1. Page after loading
I made my browser narrow to get the screenshot. Your page does not have to break between Estimatronical and Numeratoid. It can all be on one line.
Notice that the cursor is in the first input field when the page loads. The color codes are #7C8B9B and #E5EBDF.
Paula fills in some numbers and clicks the button:

Figure 2. Page after computations
The output appears only after the button has been clicked.
Notice that the cursor has gone back to the first input field.
Upload your page, and enter the URL below.
(Log in to enter your solution to this exercise.)
Create a page that looks like this when it first loads:

The user clicks on the animal that is the cutest, then the one that is the next cutest, and so on. A list of animals grows, in the order they are clicked. The mouse cursor should be a hand when it’s over one of the animal names.
Here’s what the page looks like after the first click:

Here’s what it looks like at the end:

You can watch a video showing how the interaction should work.
Match the colors approximately. Use any sans serif font. Use at least two CSS classes (you can use more).
I made my browser narrow to make the screenshot above, so I could fit it in this page. You don’t need to have the same width.
Hints:
Upload your solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
Write a JavaScript program to compute the circumference of a circle from the diameter. The user types in the diameter, clicks a button, and the program shows the circumference.
The formula is:
circumference = diameter * pi
pi is around 3.14159.
JavaScript has the value of pi built-in. If you want to try it, use Math.PI instead of 3.14159.
Upload your solution to your server, and paste the URL below.
(Log in to enter your solution to this exercise.)
Write a JavaScript program that reports the circumference and area of a circle. The user types in the diameter, and clicks a button.
The formula is:
area = pi * diameter/2 * diameter/2
Upload your solution to your server, and past the URL below.
(Log in to enter your solution to this exercise.)
Make a page with an order form like this:

Figure 1. Empty order form
Note that the input focus is in the first field.
The user completes the fields and clicks the button. Show an error message if a field is empty:

Figure 2. Empty field
Show an error message is a field has an invalid number:

Figure 3. Bad number
Show an error message if the user enters a number that is less than zero:

Figure 4. Number less than zero
If there is an error in both fields, you can just show the one for the beans field.
Once you show an error and the user clicks the OK button on the alert() box, the input focus should be in the field the error message was about. For example, after hitting OK in Figure 4, the cursor should be in the things field.
If the input data is valid, show the total price:

Figure 5. Data OK
Upload your solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
Create a page to compare the performance of two vampire fighters: KM and MS. The page starts like this:

Figure 1. Page after loading
I made my browser narrow to get the screenshot. Your page does not have to break between Compute and winner. It can all be on one line.
Notice that the cursor is in the first input field when the page loads. The color codes are #7C8B9B and #E5EBDF.
The user fills in some numbers. Here’s what it looks like after some input, but before the button is clicked:

Figure 2. Page after input
When the clicks the button, do these things:
Here’s what the display would look like after the button is clicked with the data above:

Figure 3. Page after click
Notes:
$("#thing").val(13) would set the value of the form field thing to 13.Upload your page to your server, and put the URL below.
(Log in to enter your solution to this exercise.)
Write a page that takes an order for a cake. The user makes three choices:
The page looks like this when it opens:

Figure 1. Page when it opens
When the user puts the mouse cursor over any <li> element, the cursor changes to a hand:

Figure 2. Cursor
When the user clicks on an <li> element, the text of the element appears in the output area at the bottom of the page:

Figure 3. Selecting a cake option
The output area has one part for each category of choices: size, cake flavor, and frosting flavor. When the user clicks on a cake size, his/her choice appears in the size part of the output area. And so on.
Once the user has clicked on a choice within a category, s/he can still change his/her mind. If the user clicks on a different choice, the new choice is shown in the output area:

Figure 4. Selecting a different cake option
The user can select one option in each category. For example:

Figure 5. A complete order
Finally, the user clicks the Order button, and an alert() message appears:

Figure 6. Order button clicked
Upload your solution to your server.
(Log in to enter your solution to this exercise.)
Advanced exercise
This exercise is fairly complex. You should consider working on it with someone else.
You work for Dog Brews, Inc., a distributor of fine dog beers and wines. Dog Brews buys from breweries and vineyards, and distributes to retail outlets.
There’s an order cycle for each product. Dog Brews places an order to, say, a brewery. The brewery delivers what was ordered a few days later. As Dog Brews sells the product, its inventory goes down. Before inventory gets to zero, Dog Brews places another order, and the cycle continues.
Here’s the situation over time:

Inventory jumps when an order is delivered. It goes down as products are sold. It suddenly jumps when another order is delivered. And so on.
When Dog Brews places an order, it isn’t delivered immediately. There’s a time delay. It’s called the lead time. So if an order placed on Monday is delivered on Wednesday, that’s a two day lead time.
Because of the lead time, Dog Brews doesn’t wait until inventory gets to zero before placing an order. If the lead time for a product is two days, then Dog Brews should reorder when it gets down to a two day supply of the product. If Dog Brews sells, say, 40 units a day, it would reorder when inventory gets down to 80 units. That’s called the reorder point.

Also on the graph you can see the reorder quantity, that is, the quantity ordered each time. There’s also the reorder period, also called the cycle time. That’s the time between each order.
This model makes lots of assumptions about the business, e.g., that demand is constant. The assumptions are usually not met in reality, but it’s close enough in many cases.
It costs money to place an order, with shipping, insurance, and such. The bigger the orders, the lower the ordering costs will be. But it also costs money to keep inventory. There’s storage, spoilage, theft, and so on. How to balance out ordering and storage costs?
There are some mathematical formulas that will work out the best order quantity, reorder point, and reorder period. Plug in numbers for demand, lead time, order cost, and some other things, and the formula will tell you what to do.
Your job is to write a Web page to help the mammals working in Dog Brews’ purchasing department. Here’s what the page will look like when it starts out:

The confidentiality policy label shows a hand when the mouse cursor hovers over it:

When the user clicks on the label, the policy shows up:

Click again, and the policy hides.
The user fills in the values. For example:

Clicking the button shows the results:

Here’s some JavaScript you can use to compute the output:
var optimal_order_quantity = Math.sqrt(2*demand*order_cost/(unit_cost*holding_cost/100));
var reorder_point = demand/250*lead_time;
var cycle_time = 250*optimal_order_quantity/demand;
For extra Dog Points:
Upload your solution to your server. Enter the URL below.
(Log in to enter your solution to this exercise.)
These challenging exercises may use HTML not covered in CoreDogs. Get ready to Google!
Make a page that hides detailed information until the user asks for it. My page is about dogs, but you can make yours about something else.
The page starts out like this:

Figure 1. Page at start
The mouse cursor turns into a hand when it moves over a title. When the user click on a title, two things happen. First, the arrow changes. Second, some text appears below the title:

Figure 2. After a click
Click on the same title again, and (1) the arrow changes back into a down arrow, and (2) the text disappears.
Use an animated effect to show and hide the text.
Here’s some code that might help:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
...
<script type="text/javascript">
$(document).ready(function() {
$(????).click(function() {