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.
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.
(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.
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.
Look at the URL for the page. The page’s file name is dog-house.html. All lowercase, with a dash separating the pieces of the name.
The page is about building a dog house, so that’s what’s in the <title> tag. Remember, use meaningful title tags to help users, and to increase search engine rankings.
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.
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.
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 3. 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.

You can try my solution, but no peeking at the source code!
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.
(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.
You can see my solution, but try it yourself before you look at the source code!
(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.
You can check my solution. Do the exercise yourself first, then compare your HTML code with mine.
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.
Consider what the page looks like when it isn’t styled. Here it is again:

Figure 9 (again). Page rendered
The page’s background color is white. Why? That’s the default. Unless you override it, the browser will use the default.
The text is black. Why? That’s the default. Unless you override it, the browser will use the default.
So the browser is always style rules. If you don’t give style rules yourself, the browser uses the defaults. If you add CSS rules, your rules override the defaults.
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.
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.
By the end of this lesson, you should:
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!
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.
Suppose you want to make some dog treats. One way to do it is to grab some ingredients, mix them together, and see how they taste. If the answer is “yuck!”, throw that mix away, and try again. Keep doing this, and eventually you would get something you liked.
I wouldn’t make treats that way.
Why not?
It’s so wasteful. Throwing all that stuff away? Makes no sense.
What would you do instead?
I’d find a recipe that someone else has already tested. There’s lots at DogTreatRecipes.org.
A pattern is a recipe that someone else has already tested. But it’s a recipe for Web stuff, not for dog treats.
You can save yourself a lot of time if you reuse a pattern, rather than doing everything from scratch.
Make sure you use the right pattern, though. Maybe I pick a dog treat recipe, and make the treats. Then I find out that I was supposed to make treats for humans, not dogs. Uh oh! I used the wrong pattern, because I didn’t understand the goal.
Why would anyone make treats for humans?
Training. Give them treats when they do what you want. You can train humans to do lots of stuff. Let you outside, let you inside, shake paws, you name it.
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 1. Accessing the pattern library
Look at the Basic text styling pattern. It uses the guidelines from the previous page. 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.
You might create your own way of doing something. Maybe there’s a set of colors and fonts you like. That could be a pattern for you.
Or you might see a Web page that does something neat. Make a note. Maybe look at the page’s code, to see how it’s done.
Patterns are shortcuts, right?
Yes.
But is using someone else’s shortcut always a good idea?
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 2. Title text and detail text are the same color
But maybe you want them to be different colors.
Say you’re making a site for a school that has the color scheme green and gold. These colors are part of its branding (we talked about branding earlier). You might want the title text to be green, the detail text black, and the background gold. So you need to adjust the pattern.
You can’t just throw the pattern in without understanding it. You need to understand it, and maybe change it, to fit the job.
Patterns are not like Lego bricks that you can snap together. They’re more like cookie cutters.

Figure 3. A cookie cutter
Image from WikiHow.
You can just stamp out the basic shape. But if you need to, you can 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 4. 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. 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
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.
Here’s my solution. No peeking at the source code until you’ve tried it yourself!
(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
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.
Here’s my solution. No peeking at the source code until you’ve tried it yourself!
(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.
Here’s my solution. No peeking at the source code until you’ve tried it yourself!
(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.
Here’s my solution. No peeking at the source code until you’ve tried it yourself!
(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 for more exercises.
It’s important that you do the exercises, if you want to learn anything.
Create a page that looks like this, using CSS styles:

You can see my solution, but don’t look at the source code until you try it yourself!
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:

You can see my solution, but don’t look at the source code until you try it yourself!
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:

You can see my solution, but don’t look at the source code until you try it yourself!
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:

You can see my solution, but don’t look at the source code until you try it yourself!
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:

You can see my solution, but don’t look at the source code until you try it yourself!
Upload your solution to your server. Put 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.
Take it slowly. In fact, really slowly for someone as anxious as you are, CC. Baby steps. I’ll help you along.
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 this when they decide what goes into each chapter.
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
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
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.
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
This will download jQuery from one of Google’s servers.
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.
On this page, you’ll learn how to:
Here are the steps involved in writing a simple program.
Let’s see an example. Suppose we want users to fill in a form on a Web site. We want to 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.
You can see the final page. Click on “Show instructions” and see what happens. (The “v” represents an image of a down arrow.)
A good way to get started is to write down:
Argh!! Big words!
Calm down. They’re big words for simple things. Don’t switch off. It will all make sense.
A state is the way something is at a point in time. For example:
Events cause changes between states. The alarm clock triggers a change between the sleep and wake states. Seeing a squirrel causes changes in your state and the squirrel’s state.
The Web page for our example will be in two different states:
It helps to draw the states on paper, like this:

Figure 1. Planning states
In the “Instructions hidden” state, the help prompt is “Show instructions” with a down arrow, and the instructions are hidden. In the “Instructions showing” state, the message is “Hide instructions” with an up arrow, and the instructions are showing.
So that’s the states. The various ways the Web page can look.
Recall that events are things that happen, like users clicking on things. State transition diagrams show the events that trigger state changes.
Oooo… “state transition diagrams” sounds so geeky and cool. Impress your friends.
Friend: Hey, what are you doing?
You: Working on a state transition diagram. It’s a programming thing.
Friend: Oh. (Walks away, thinking you must be über smart.)
Here’s a state transition diagram for this program:

Figure 2. State transition diagram
A click on the help prompt (Show instructions or Hide instructions) moves to the other state.
OK, so it’s not complicated. But “state transition diagram” still sounds impressive. Just don’t use the acronym STD. That means something else.
jQuery has a click() event. We can use that.
There’s one other jQuery event we’ll need: ready(). A ready() event happens just after a Web page has finished loading. Usually you put initialization code in the ready() event. That’s code that runs once, to finish getting the page ready for the user.
In jQuery, one of the things that the ready() event does is set up the other events. There are thousands of possible events that can happen on a particular page. For example, you could let the user click on every different character on the page – every a, b, c, 1, 2, 3, ... – and run some code.
Rather than having the browser watch for every possible click() event, you tell jQuery which events you want it to watch for. You do this in the ready() event, the first thing triggered when the page is shown.
What I normally do at this stage is write the HTML I need. Remember that most JavaScript code messes with HTML objects, like paragraphs.
Here’s some HTML for this example:
<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 3. 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 4. 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 i. In our example, we need to mess with two things:
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 5. 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.
Let’s begin by creating the page that we’re going to attach code to.
<!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>
<p id="instructions_title">Show instructions v</p>
<blockquote id="instructions">
Helpy help help.
</blockquote>
<p>FORM</p>
</body>
</html>
Figure 3. Starting out
I’ve included all the things that will show on the page eventually, even if they’re not shown when the page is first display. For example, the instructions are not shown when the page is first displayed. But they will be.
Note that I’ve loaded jQuery.
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.
I’ll start this program by hiding the instructions when the page loads. This code goes into the head. Or somewhere.
<script type="text/javascript">
$(document).ready(function() {
$("#instructions").hide();
});
</script>
Figure 4. Hiding instructions
Everything between $(document).ready(function() { and }); runs once the page has been loaded. Don’t worry about why it looks like this. Just copy-and-paste these two lines, and know that it works.
The $("#instructions") 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, the statement 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.
I could write the rest of program in one step, but I won’t. I’ll just see if I get the event binding to work. Remember that this ties some code to an event.
I’ll 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").click(function() {
alert("Clicky clicky.");
});
});
</script>
Figure 5. Eventing
You can try it.
Notice that the event binding is done within the ready() event. Remember that ready() runs after the page has been loaded. This makes sure that the element the code is bound to exists before the binding is attempted.
$("#instructions_title") means “find everything with an id of instructions_title.” There is only one thing with that id. .click(function() { means “Here’s what to do with the user clicks on it.” You can just copy-and-paste this, along with the }); that closes the event code.
What happens when the user clicks? S/he gets a message. Try it if you haven’t already.
For the next step, I’ll do this:
<script type="text/javascript">
$(document).ready(function() {
$("#instructions").hide();
$("#instructions_title").click(function() {
$("#instructions").toggle('slow');
});
});
</script>
Figure 6. Toggling visibility
You should try it.
$("#instructions") means “Find everything with an id of instructions. .toggle('slow') means “Toggle its visibility.” If it’s showing, hide it. If it’s hidden, show it. 'slow' means to do it slowly – which is still kind of fast in jQuery. You can use 'medium' or 'fast' as well or leave it out, which would be .toggle().
You can also do something like .toggle(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, so you should get to know it.
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.
Here’s my solution. Don’t look at the source code until you’re tried it yourself!
(Log in to enter your solution to this exercise.)
I’ll add one line.
<script type="text/javascript">
$(document).ready(function() {
$("#instructions").hide();
$("#instructions_title").click(function() {
$("#instructions_title").text("Hide instructions ^");
$("#instructions").toggle('slow');
});
});
</script>
Figure 7. Changing instructions
$("#instructions_title") says “Find everything with an id of instructions_title.” .text("Hide instructions ^") says “Replace the text with Hide instructions ^.” So this actually changes the content on the page.
Change your secret program so that when the user clicks on secret_instructions, its text changes to “The secret is:”
Upload your solution to your server, and enter its URL below.
Here’s my solution. Don’t look at the source code until you’re tried it yourself!
(Log in to enter your solution to this exercise.)
Try this version of the page. Notice that the mouse cursor changes to a hand when the mouse pointer moves over the instructions_title. This gives the user a hint that the element is clickable.
I added the following to the page:
<style type="text/css">
#instructions_title:hover {
cursor: pointer;
}
</style>
Figure 8. Styling the cursor
There are three new things here. First, there’s the # in front of the selector. This is same thing that jQuery uses. #instructions_title means “find the thing with the id of instructions_title. In fact, jQuery borrowed this syntax from CSS.
What this means is that the styles in the { } will be applied only to instructions_title.
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:hover {
cursor: pointer;
font-weight: bold;
font-size: 24px;
color: red;
background-color: yellow;
}
</style>
Figure 9. Going too far
Well, you could do this, but I wouldn’t recommend it. The point is, you can change anything.
The final new thing in Figure 8 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.
Write a program to show the first part of a dog joke:

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

You can see my solution. Don’t look at the source code until you’ve tried it yourself!
Upload you solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
There are two other things we’d need to do to make this example actually useful.
instructions_title back to Show instructions v on every other click.You’ll learn how to do these things later.
On this page, you learned how to:
All cool stuff!
Let’s get some data from the user and do stuff with it.
On the last page, you learned how to add interactive help to a Web page. W00fish! Not just static pages anymore.
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 the 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:
You know what the id attribute does. It lets you tell jQuery what element you want to mess with. 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:
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. 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>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.</p>
<input type="text" id="user_name_input">
<button type="button" id="go">Go!</button>
<h1 id="user_name_output"></h1>
</body>
</html>
Figure 1. Starting “Hello world!”
Please have a look at the result.
Line 18 creates a text input field. Line 19 creates a button right next to it. Line 20 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.
var user_name = $("#user_name_input").val();
//Add it to the output.
$("#user_name_output").text("Hello " + user_name + "!");
//Show the output.
$("#user_name_output").toggle('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. Comments are for Webers, not browsers.
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. A variable is a temporary holding place in the computer’s memory. var thing tells the browser to grab some memory and label it thing. var user_name tells the browser to grab some memory and label 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. "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.
var 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 various things into it, like Tim, or Lenny, or Katherine.
"Tim" is a constant. It will always be, well, "Tim". The “s are JavaScript’s way of representing fixed text.
Line 2 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.
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.
var 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.
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 “ around them. Single quotes will also work, like ‘CC’.
Here’s the “Hello world!” program again.
$("#go").click(function() {
//Get the user's name.
var user_name = $("#user_name_input").val();
//Add it to the output.
$("#user_name_output").text("Hello " + user_name + "!");
//Show the output.
$("#user_name_output").toggle('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 6 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 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. 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() {
var 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() {
var 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 on your page. You can do the same thing with CSS: put the CSS rules in a separate file, and include them.
Look at line 6. This includes the CSS file game2.css. Here’s the 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 nothing new in the CSS rules themselves. Just the usual fonting and coloring.
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.
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.
Here’s my first attempt at 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">
<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 is new.
Copy-and-paste the code in Figure 1 into your own file. Run it from your development server.
Now, try the page with and without the mystery line, the one with the .focus() in it. The easiest way to do this is to temporarily comment out the line. Changing it to:
//$("#meal_cost").focus();
will make the browser ignore the line. Remove the // to put it back into the code. Remember to tell your browser to reload the page when you make a change.
What does the mystery line do?
(Log in to enter your solution to this exercise.)
Now to finish. 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.
var meal_cost = $("#meal_cost").val();
//Compute the tip and total.
var tip = meal_cost * 0.15;
var 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:
var 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
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.”
How to do this? Change the code to:
var 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.
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
You can try my solution, but don’t look at the code yet!
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.
var meal_cost = $("#meal_cost").val();
//Get the number of diners.
var humans = $("#humans").val();
//Compute the tip and totals.
var tip = meal_cost * 0.15;
var total_cost = parseFloat(meal_cost) + parseFloat(tip);
var 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 mean cost is divided up in line 18. There isn’t a parseFloat() here, 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().
You can try my solution, but don’t look at the code yet!
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.
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.
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().
You can try my solution, but don’t look at the code yet!
Upload your solution to your server, and put the URL below.
(Log in to enter your solution to this exercise.)
You’ve learned to make pages start doing things. You learned:
text().You’ve started to learn some simple programming. But 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 a lot 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.
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 1. 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 2. 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 3. Broken JavaScript
To try it, click on this link.
Now check the error console. This is what I see:

Figure 4. 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 it 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 5. 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.
I had some problems in the last lesson, the computations one. I wish you’d put this debugging lesson before that one.
It’s a chicken-and-egg thing. You can’t debug code if you don’t know to write any code. And you’ll know how important debugging skills are if you’ve struggled a little first.
By the way, frustration is normal when doing computer work. You need ways of handling it. Know how to:
Or you could be like this guy.
So 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 often 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() {
var input_number = $("#input_number").val();
var 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 6. 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");
var input_number = $("#input_number").val();
var square = input_number * input_number;
$("#square").text(square);
alert("Ending the click function");
});
alert("Ending the ready function");
});
</script>
Figure 7. 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 8. 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() {
var input_number = $("#input_number").val();
var square = input_number + input_number;
$("#square").text(square);
});
});
</script>
Figure 9. A different problem
Try the page. You get output this time, but it’s wrong:

Figure 10. 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");
var input_number = $("#input_number").val();
alert("input_number:" + input_number);
var square = input_number + input_number;
alert("square:" + square);
$("#square").text(square);
alert("Ending the click function");
});
});
</script>
Figure 11. alerts
Look at lines 12 and 13:
var 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 12. Showing variable values
You can try the page.
So, we know that this line is causing the problem:
var square = input_number + input_number;
Aha! The + should be *! Change it, and the page will work.
W00f!
Fix the bugs in this page.
You can try my solution, but do it yourself first!
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 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:

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(){
var 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:
var 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
You can see my solution, try it yourself first.
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.
var 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
You can try my solution.
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:
var age = $("#age").val();
if ( age == "" ) {
alert("Please enter your age.");
}
else {
var 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.
This example also shows you how flexible strings are. You can assemble five components (line 24). You can include computations, like the (age - 1) in line 25.
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
You can try my solution. As always, try it yourself first.
(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.
var 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 ) {
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:
You can try my solution.
Upload your solution to your server, and put the URL below.
(Log in to enter your solution to this exercise.)
You can combine the tests, like this:
else if ( age < 0 || age > 120 ) {
alert("Please enter a valid age.");
}
This means “if age is less than 0 or age is greater than 120.”
|| means “or.” It returns true if the test on either side is true. The | character can be hard to find on your keyboard. Here’s where it is my keyboard:

Figure 8. The | key
You can’t omit age the second time, like this:
else if ( age < 0 || > 120 ) { //WRONG!
Here are all the “logical operators,” as they are called.
&& |
is equal to |
|| |
is not equal to |
! |
is not |
Figure 9. Logical operators
Here are some more examples.
if ( name == "Renata" || name == "CC" ) {
If
nameis Renata or CC.
if ( temperature > 0 && temperature < 100 ) {
If
temperatureis between 0 and 100.
if (hair == "blond" && eyes == "blue") {
If hair is blond and eyes are blue.
if (! (hair == "blond" && eyes == "blue") ) {
If it is not true that hair is blond and eyes are blue.
Create a page to check whether a sound is in the frequency range of human hearing. Healthy young humans can hear sounds between 20 hertz and 20,000 hertz. (Of course, we dogs can hear higher sounds, up to 60,000 hertz. Those silly humans.)
The page should look like this:

Figure 1. Human hearing
Show an alert message, depending on what the user typed.
You can see my solution. Try it yourself first, of course.
Upload your solution to your server. 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:
There are some exercises on the next page. You should do them. It’s the only way you’ll understand this stuff – do it.
The only way to learn to create Web pages that can ask questions is: make some Web pages that ask questions.
Remember, Webers need to be able to do things. Not just talk about them.
If you get stuck, ask for help in your study group.
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. You can try it here, but don’t look at the source code.
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 circumference of a circle from the diameter. The user types in the diameter, clicks a button, and the program shows the circumference. You can try it here, but don’t peak at the source code!
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. You can try it here, but don’t look at the source code!.
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.)
Write a JavaScript program to compute the length of the hypotenuse of a right triangle from the length of the other two sides. You can try it here, but don’t peak at the source code!
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.)
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:
You can try my solution.
Upload your solution to your server. Enter 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
You can try my solution, but don’t look at the code yet!
Upload your solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
Images are very important on the Web. A single glance at an image can give users lots of information. They also help set the mood for a site.
You need to know how Webers think about images. What are they for? Where do you get images for a project? What software do you need to have?
That’s what this lesson is about.
You’ll also learn how to manipulate images with jQuery. This is Much Fun. You’ll show them, hide them, resize them, all with animated effects. You can use these techniques to create sophisticated Web 2.0 interfaces.
Finally, you’ll learn how to use JavaScript’s if statement. For example, you might show different images on a page, depending on what language the user speaks. Or maybe different images for different times of day.
By the end of this lesson/page, you should:
if statement.This is the last lesson that deals with individual Web pages. Starting with the next lesson, we start working on entire sites.
Onward! To destiny!
By the end of this page, you should:
Images serve three main purposes: informational, interface, and structural. These are not completely separate categories. Some images have multiple functions.
Informational images are on a page because they are part of the content of the page. They have meaning, offering information about the page’s topic. If a page is about tractors, an informational image will tell users something about tractors. If a page is about bow ties, an informational image will tell users something about bow ties.
Photographs are the most common informational images. Suppose we’re creating a page about bulldogs. We might add a photo of a bulldog, so users will know what one looks like.

Here’s another example. Let’s say you’re writing a page about making dog biscuits. You have the text:
Quickly stir the mix with a whisk.
You might have a photo to show what a whisk is:

The photo contributes to the content, that is, it helps people understand how to make dog biscuits.
Er, won’t everyone know what a whisk is?
Most people will. But remember two things.
First, some people are new to cooking. Maybe they’re youngsters, just getting started.
Second, people have different names for the same things. Maybe a “whisk” is called something else in Belgium. I don’t know.
Where did you get that photo?
From stock.XCHNG. The photo was posted by the user LittleMan.
Informational images are often photos, but not always. Drawings, maps, screenshots, and other things are informational images as well.
Some informational images convey emotion. Like this.

How you can not look at that and go, “Awwww…”
Users click, drag, or otherwise interact with interface images. Here are some buttons:




Structural images are part of the visual framework of a Web page. They’re used to separate parts of a page, highlight some areas, and so on.
There are some common types of structural images.
Dividers break up sections of a page.




Bullets are often used with list items.




Banners are used for page titles. The ones below are blank. Use a graphics program to add text.




You need to know what images to use when. Here are some guidelines.
Informational images should be useful, that is, they should give users information they need. For example, a map that’s too small or too blurry will not help people find your business.

The mood of each image ought to fit the message. Here’s a photo that fits the text.

The palette of each image should match the color scheme of your site. We’ll talk more about color later in this chapter.
The image shouldn’t be so big that it pushes other page elements out of position. And like the map above, it shouldn’t be so small that it’s useless.
Small is good, as long as you don’t sacrifice too much quality.
People often make mistakes with images from digital cameras. Most images should be shrunk and cropped before they’re shown on a Web page.
This is very important. You, your clients, your employer, could be in Big Trouble if you violate copyright. There are plenty of places where you can get free or low-cost images. If in doubt, find a different image.
Every Weber needs to know how to do some basic image tasks.
We’ll talk about these tasks later.
You should also consider learning how to:
A Weber might say, “I’m a PHP programmer. Other people handle those details. Why should I learn this stuff?”
Again, it’s a matter of employability. It’s a matter of how much value you can create with your Weber skills.
Don’t underestimate the importance of images. Take the CoreDogs page on Web page structure, for example. If you look at it, you might guess there are about eight images on it.
There are about 30.
The + and – in the menu, the arrows on the “My notes” field, the backgrounds for the buttons. They’re all images.
Most images on the Web are simple. You can make almost all the images in an entire site with just a few basic skills. But if you don’t have any image skills at all, you’ll need to call on someone else whenever you need an arrow or a button.
That delays your work. It makes you less productive.
It also means that you can’t take on complete projects by yourself. The Web is a great place for entrepreneurs. You can start your own business, just like I started CoreDogs. But entrepreneurs need to know a little about lots of things. Weber entrepreneurs need to know how to do basic image work.
Learn some basic image skills. It will make you more valuable to clients and employers. And it will come in handy when it’s time to start your own business.
On this page, you learned:
Let’s take at look at the three main image formats used on the Web.
You learned that images serve two purposes: informational and structural. You know that it’s important to have basic image skills.
This page starts building those skills by exploring how computers display images.
By the end of this page, you should:
Every image on your computer’s screen is made up of pixels. A pixel is a tiny dot of color. When the pixels are small enough, your brain merges them together into a single image.
Here’s an example.
![]()
Figure 1. Pixels
The photo is of Renata when she was about two months old. Her eye is zoomed by 1,100%, so you can see the pixels.
Images made of pixels are often called bitmaps.
Each pixel is made up of three different colors: red, green, and blue (RGB). By mixing different amounts of red, green, and blue, your computer can show any color your eye can see.
The most common way to represent colors in Web work is as RGB codes. Each channel (one for each color) has a number from 0 to 255. 0 means none of the color. 255 means as much of the color as the computer can show.
Why 0 to 255? It has to do with bits, bytes, and powers of two. Really geeky stuff. Let’s decide we don’t care.
Here’s the color (255, 0, 0):
Full red, no green, no blue.
Here’s the color (0, 255, 0):
No red, full green, no blue.
You can mix colors. Here’s the color (128, 32, 64):
So each dot in Figure 1 has three numbers for its color. For example, this color:
is in the image. It’s (250, 206, 161).
There are two colors you should know by heart. (0, 0, 0) means all the colors are off. That shows as black, like my fur. (255, 255, 255) means all the colors are on full. That shows as white.
Photos have thousands of different colors, captured by a digital camera or a scanner. Text and drawings have fewer colors.

Figure 2. Text
This text has only two colors: white (255, 255, 255) and dark red (157, 16, 16).
But the text is jagged. How about this:

Figure 3. Anti-aliased text
This uses anti-aliasing to make the text look better. Where two contrasting colors meet, the computer works out an average color, and uses that to blend the two together. Anti-aliased images look smoother.
You learned:
Now let’s see how different file formats store color information.
You learned how computers show images on a display. But how they’re stored in files is different. That’s what this page is about.
By the end of this lesson/page, you should:
It takes a lot of pixels to make a big image. And each pixel needs three different numbers to represent it. The result? Lots of data, and long download times over the Internet, especially for slow connections.
An image format is a way of storing an image in a file. The most obvious format is simply to store all of the numbers for all of the pixels. That’s what a raw image file is, as it comes from the image sensor of a digital camera.
Computerists have come up with clever ways of compressing images, so that they can be stored in smaller files. An “image format” is a way of encoding image data to store in a file.
There are about a bazillion image formats out there. But the vast majority of Web images use only three formats.
A raw image will contain many more colors than your eye can see. JPEG reduces file size by dropping colors from images, and averaging colors in adjacent pixels.
Let’s be clear what is happening. In the previous lesson, you saw programs like this one for computing a tip at a restaurant:
Get the meal cost from the user.
tip = meal cost * 0.15
total = meal cost + tip
Show tip and total to the user.
This is an algorithm. An algorithm is a set of steps for performing some task. “Algorithm” and “program” mean more-or-less the same thing.
What does this have to do with JPEG?
JPEG stands for the Joint Photographic Experts Group. A bunch o’ dude/ttes got together, and agreed on an algorithm to compress pixel data. They came up with something like this:
Convert from RGB to YCbCr.
Reduce the resolution of YCbCr chroma data.
Split the image into blocks of 8×8 pixels.
...
Got it? No, neither do I. But that’s OK. It works.
So the JPEGers agreed on this algorithm. Then some programmers got to work. They wrote two types of programs.
When your Web browser shows a JPEG, it downloads the encoded file from the Internet, decodes it, and gives the decoded data to your computer’s operating system (Windows, OSX, Linux) to show on your display. So your browser has a JPEG decoder built into it, or has one that it can call on.
JPEG files almost always have the extension .jpg.
JPEG is a lossy format, that is, it compresses by throwing away information. Usually that’s OK, because your eye can’t see all of the colors in the raw image anyway. But it can be overdone. Here’s a photo that’s been compressed too much.

Figure 1. Compressed too much
The good news is that the image file is tiny. Too bad it’s junk.
JPEG is best for photos, that have thousands of colors. Throw some away, and your eye won’t notice.
The GIF format is lossless, that is, it doesn’t throw away information. At least, it tries not to. The trouble is that it limits each image to 256 different colors. The set of colors in an image is called its palette.
That sounds like a lot, and it is for most structural images, like buttons and dividers. But the GIF format is lousy for photographs, which can have thousands of colors.
GIF also has problems with heavily anti-aliased images. As we saw earlier, anti-alias works by adding colors to an image. If an imagine has lots of different color boundaries that need to be anti-aliased, GIF might not be able to handle it.
GIF files have the extension .gif.
The GIF format can do two things that JPEG cannot. One is animation. Here’s an animated GIF.

Figure 2. Animated GIF
It’s made of a bunch of still images shown in a loop. Here are the frames:




Figure 3. Animated GIF frames
Use animated GIFs sparingly. Many Webers view their overuse as the mark of an amateur.
The other feature that GIF has that JPEG does not is transparency. One of the colors in a GIF image’s palette can be set to transparent. Your GIF decoding software simply skips transparent pixels, not showing them at all. That lets anything underneath show through.
Here’s a GIF of a cow on different colored backgrounds.


Figure 4. Transparent GIF
The portable network graphics (PNG) was designed to replace GIF. PNG is lossless, can put thousands of colors in a single image, and supports translucency. PNG does not support animation. PNG files have the extension .png.
I said that PNG supports translucency, while GIF supports transparency (actually. PNG supports both). I’m using the terms in different ways. Not all Webers define them this way, but some do.
A transparent pixel is either all on, or all off. In a GIF image, a pixel is one of the colors from the palette, or it isn’t there are all. The cow in Figure 4 has a transparent background.
A PNG can add an optional fourth channel for each pixel. So there’s a red channel, a blue channel, a green channel, and an alpha channel. The higher the value in the alpha channel, the more of the color is used.
Here’s a flamingo:

Figure 5. PNG flamingo
Here’s a blue spot:

Figure 6. Blue spot
The spot’s pixels get more translucent around the edges the of the spot.
You can see the translucency when you put the spot on top of the flamingo:
Figure 7. Blue spot on the flamingo
This isn’t a different image. It was made by overlaying the two images above.
When the spot’s pixels are not translucent (in the center of the spot), they hide the flamingo’s pink pixels. But when the pixels are translucent (at the edges of the spot), your computer blends the blue with the pink.
Here’s another example. Suppose I wanted a searchlight effect in an ad.
Search for savings!
Figure 8. Searchlight
The pixels in the searchlight have some translucency, so the text underneath always shows through.
The opposite of translucency is opacity. The more translucent something is, the less opaque it is, and vice versa. A translucency of 80% is the same as an opacity of 20%.
There are other graphics formats, but they don’t impact the Web as much as the Big Three. We won’t talk about them.
Use JPEG for photos, but don’t overcompress. Use PNG for new drawings. There are a lot of existing GIF images you can use on your sites. There’s no need to convert them to PNGs. Just use them as is.
We’ve been talking about still images. There’s also movies and animation.
The easiest way to show a movie is to upload it to YouTube. Then you can put some code into your page to embed the movie in your site. See YouTube for details.
Flash is the top dog of animation technology. Flash could be a CoreDogs book in its own right. See Adobe’s site to get started with Flash.
On this page, you learned about the Big Three formats: JPEG, GIF, and PNG. You learned about transparency and translucency.
Let’s talk about where you can get images for your pages.
You know what images are for (information or structure), that they’re made of pixels and color codes, and that they’re stored in one of the Big Three image formats.
But where do you get images?
Images come from two source. You make them, or someone else does. By the end of this page, you should:
Humans have created millions of images you can use on your Web sites. Before you use an image, make sure you understand its licensing terms.
There are many different licenses. In fact, image owners can make up any license they like. For example, a photographer might say that you can only use her images for free on alternate Tuesdays.
But some licenses are more common than others. Here are some samples.
Note that I am not a legal expert. I don’t guarantee anything about this. YMMV.
When in doubt, check. For example, take the paw prints in the header image at the top of this page. I got the image from Dog Paw Print. I didn’t want to follow the exact image terms on the site, so I emailed the site’s owner, asking permission to do something a little different. She wrote back immediately, giving permission.
Let’s look at some image sources.
BurningWell is a collection of public domain photos. The collection is not large, but there’s still a lot of stuff there, and all for free.
morgueFile is one of the better known free photo sites. The images can be used for commercial purposes. The photos are categorized and searchable.
Links to various government sites. Most images are in the public domain, but not all.
This service lets you license images from photographers around the world. Image licenses start from around under $1 per image. You’ll find photos of just about anything here. They have over 4.5 million images at the time of writing.
You can buy images to use on your Web site from $1 each. There’s some great stuff here.
Stock.XCHNG is is part of this family of Web sites. Images can be used for free, with some restrictions. Check the license.
Like stockxpert. Same parent company, in fact.
There are hundreds of sites with free or low-cost images. Add your favorites to the links list.
Every Weber should have a digital camera, even if it’s just in a cell phone. You never know when you’ll get an opportunity to take a cool photo. And maybe one of your photos will show up on FAIL Blog!
When you buy a cell phone with a camera, make sure there’s an easy way to move images to your computer.
Every Weber should be able to make simple drawings. We’ll talk about that on the next page.
That’s where the robot dog came from. Zombiecatfire13 drew it, and said I could add it to CoreDogs.
If you have a dog drawing you did, send it to kieran@coredogs.com. I’ll find a place for it. I’ll link your image to somewhere. Give me the URL.
There are many sources for free and low-cost images. Make sure you follow license terms. When in doubt, ask.
Let’s cover some of the tools that should be in your image toolkit.
You need to have software to create and manipulate images. Let’s talk about some of the free tools that are available.
By the end of this page, you should:
Image editors let you mess with the pixels in images. You can resize, crop, and perform other operations on photos and images.
GIMP is a well-known, powerful, and mature tool. I use it for most of my image work. GIMP is not the easiest to learn. But when you do learn it, you can do anything you want.
GIMP is not a very good drawing tool. Even creating simple rectangles and circles is clumsy with GIMP. But when it comes to cropping, resizing, recoloring, fixing artifacts in photos, and other photo-oriented tasks, GIMP shines.
Paint.NET is another popular tool. Easier to use than GIMP, although less powerful. It can handle common Web image tasks, though some things like dodge and burn are not as easy as they might be.
There are many other free and low-cost image editors out there. Please add your favorite to the links list.
Download and install either GIMP or Paint.NET.
Let’s look at some tasks you might do with these tools.
Often you want to focus on just part of something in a photo. Take this one, for example:

Figure 1. Awww
Maybe we just want the puppy’s head. (In the photo, I mean. You are sick!) So I’ll crop just that part of it.
Suppose I’m using Paint.NET. I’ll open the file, and use the select tool to select the part of the photo I want.

Figure 2. Selecting
Now I choose the crop command.

Figure 3. Cropping
I end up with a cropped image.

Figure 4. Cropped image
I can save it in a new file, and use it on a Web page.
Maybe I want to use the puppy head photo as a small icon. I select Image | Resize from the menu in Paint.NET. I get this:

Figure 5. Resizing
The image is 128 pixels wide, and 130 pixels high. I have to be careful to maintain the ratio between width and height. Let’s say I make the new width 90, and the height 40. Here’s what I’ll get:

Figure 6. Squished image
Not so good. Fortunately, Paint.NET will maintain the right ratio for me. I just leave “Maintain aspect ratio” checked. This feature is in GIMP, and every capable photo editing program.
I’ll make the image 50 pixels high, and leave the width alone. The software will compute that for me. I end up with:

Figure 7. Puppy icon
Another common task is to add text to a photo. Check I Has A Hotdog! for examples.
Here’s the image I started with:

Figure 8. Renata and ball
The first thing I did was add a layer. A layer is like a clear plastic sheet on top of an image. You can draw on the layer without messing up the pixels underneath. Layers are important. Every useful tool supports them.
I add the text into the new layer.

Figure 9. Adding text
I got:

Figure 10. Meat taste
To make the text look a little better, I added a slight raised effect. I copied the text layer, changed its color, moved it a little, and blurred it a little. This was the result:

Figure 11. Meat taste, raised text
The difference is subtle, but it’s there.
When you have hundreds of images on your computer, you need some way to quickly look at and manage them. For example, it helps if you can see thumbnails of all images in a directory.
I use IrfanView. Like other viewers, it can perform basic operations on files, like resizing. The thumbnail feature is OK, but buggy.
What’s your favorite? Got any tips? Consider writing an article.
Drawing tools let you create drawings like this, from the Ajax lesson.

Figure 12. Ajax drawing
It combines a photo, screen shots, an icon, text, geometric shapes (the circles around the numbers), and lines with arrows.
Let’s look at a sample task. It will show you some of the features you should look for in a drawing tool. We’ll look at OpenOffice Draw, the program I use with CoreDogs.
I made this image.

Figure 13. Dog happiness
How?
First, I started with the dog drawing. I got it from WP Clipart, a collection of public domain clip art.
Here’s the original drawing:

Figure 14. Original drawing
There are some artifacts around the dog. Artifacts are errors, extra pixels or changes in pixel colors. They usually result from problems in image scanning or format conversion.
I used GIMP to crop the image and erase extra pixels around the head.

Figure 15. Removing artifacts
Notice that I had zoomed in to 400% so I could work more easily. The broken circle near the top of the image in GIMP’s erase tool.
Once the artifacts were gone, I saved the dog head as a PNG. Then I told Draw to insert it. That’s one feature you’ll need in a drawing program: the ability to insert bitmap files. Recall that a bitmap is an image made of pixels. JPEGs, GIFs, and PNGs are all bitmaps.
Next, I added some text:

Figure 16. Adding text
I set the type face to Trebucet MS, the size to 10 pixels, and the color to dark gray.
Drawing programs work differently from photo editors. In editors like GIMP and Paint.NET, everything (most things, anyway) is a pixel, or a bunch of pixels. That makes sense for photos are other images that are pure bitmaps.
In a drawing program, drawings are made up of objects. Objects are things like text, lines, shapes, and bitmap fragments that can be moved, sized, and formatted independently.
When you use a drawing program, you insert and format the objects that make up the image. When everything is right, you create a bitmap version in a JPEG, GIF, or PNG. This is sometimes called exporting the image, or it might be saving in a different format. I actually used screen capture for this step, as we’ll see later.
So far, I have a bitmap object, and a text object. Then I added a connector:

Figure 17. Adding a connector
A connector is a line that connects other objects. Notice the anchor points, the blur crosses around the text, and the small gray rectangles around the edges of the bitmap’s selection rectangle. I anchored the connector to a point on the text, and a point on the bitmap.
You should look for a drawing tool that supports anchor points. Why? Because you can move objects, and the drawing tool will redraw connectors for you.
Here’s what happens if I move the text.

Figure 18. Moving the bitmap
Now I’ll move the text again, and change the anchor point.

Figure 19. Moving the bitmap again
The drawing program redrew the curve for me. That’s important! Choose a draw tool with connectors and anchors. It will make your life easier.
Also notice that the connector is a curved line. Curved connectors often look better on drawings with just a few objects. To me, anyway.
Here’s the target image again.

Figure 13 (again). Dog happiness
Next I added the heart. I didn’t have to draw all of the lines separately. Draw includes a bunch o’ geometric objects: ovals, rectangles, talk balloons, triangles, smiley faces, jewels, jigsaw pieces, ... Each one can be sized, shaped, and colored independently.
Look for a tool that includes geometric objects.
Finally, I added a gradient to the heart:

Figure 20. Adding a gradient
You can see from the tabs at the top of Figure 20 that I could have filled the heart with a bitmap, hatching, and other things. Look for features like this in a drawing tool.
Now that I finished the draw, I wanted to put it in a file in one of the Big Three formats. I generally use two of the: JPEG for photos, and PNG for drawings. I created a PNG for this one.
The version of Draw I’m using at the time of writing has trouble with anti-aliasing when it exports drawings. Recall that anti-aliasing reduces jaggies. What to do?
I use screen capture instead. Draw does anti-aliasing fine on the display.
There are many screen capture programs. Two good ones are PicPick and Gadwin PrintScreen. You can capture full screens, the current window, or an area you select with a mouse. Then you can save what you capture into a file.
Create a drawing using bitmaps, text, and connectors (and other object types, if you want). It could be a family tree, instructions for doing something, ... whatever you want.
Use export or screen capture to make a Webable version of the drawing. You’ll use the image soon.
(Log in to enter your solution to this exercise.)
On this page, you learned about image editors, image viewers, drawing programs, and screen capture programs.
Now that you have some images, let’s see how we show them on a Web page.
You know how to find images for your Web pages, and how to create your own. Now you’ll learn how to show the images on Web pages.
By the end of this page, you should know how to use the <img> tag to show images.
<img> tagUse the <img> tag to show images on a Web 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>Happiness</title>
</head>
<body>
<h1>Happiness</h1>
<p>What makes a dog happy?</p>
<p><img src="food_love_happiness.png"></p>
</body>
</html>
Figure 1. Happiness
Give the <img> tag the file to show, in the src attribute, and there it is. You can see the page.
<img> is an inline tag. It usually appears inside a block tag container like <p>.
Here’s another version of the same 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>Happiness</title>
</head>
<body>
<h1>Happiness</h1>
<p>What makes a dog happy?</p>
<p><img src="http://coredogs.com/content_media/lessons/clientcore/web_page_with_images/food_love_happiness.png"></p>
</body>
</html>
Figure 2. Absolute happiness
You can see this page as well.
You won’t see any difference the way the pages are rendered.
The only difference in the code is at line 10. Let’s look at what’s going on.
Take the version in Figure 2 first. The browser downloads the HTML. It finds the <img> tag, and knows it needs to grab another file from the server. It takes the URL from the src attribute:
http://coredogs.com/content_media/lessons/clientcore/web_page_with_images/food_love_happiness.png
This is an absolute URL, also called a fully-qualified URL. It contains all the information the browser needs to get the image file.
What does the browser do? It contacts the server named in the URL – coredogs.com – and asks for the file /content_media/lessons/clientcore/web_page_with_images/food_love_happiness.png. The server sends the file, and shows it.
Now, let’s look at the same line in Figure 1:
<img src="food_love_happiness.png">
The browser knows that it has to download the file with the image. For that it needs a URL. But the src attribute contains only part of a URL. Where’s the name of the server? Where’s the file path?
When a browser sees a partial URL like this in an HTML page, it does the following:
<img> tag.src attribute.Let’s see what that does in our case.
1. Take the URL of the page containing the <img> tag.
That would be:
http://coredogs.com/content_media/lessons/clientcore/web_page_with_images/happiness.html
That’s what you’ll see in the browser’s address bar if you look at the page.

Figure 3. Page URL
OK, on to the next step.
2. Strip off the name of the HTML file.
The HTML file is happiness.html, so that would leave:
http://coredogs.com/content_media/lessons/clientcore/web_page_with_images/
3. Append the contents of the src attribute.
The src attribute is food_love_happiness.png, so we end up with:
http://coredogs.com/content_media/lessons/clientcore/web_page_with_images/food_love_happiness.png
That’s the complete URL of the image. You can verify this if you copy it and paste it into your browser’s address bar:

Figure 4. Image URL
A URL like the one in src="food_love_happiness.png" is called a relative URL, because it’s relative to the HTML page the URL is in. When a browser gets an <img> tag with a URL containing just a file name, it asks the server for a file in the same directory as the HTML file containing the <img> tag.
Webers almost always use relative URLs, not absolute URLs. It makes sites easier to manage. Let’s say I wanted to rename the ClientCore book, and call it BrowserCore. The new location of the image would be:
http://coredogs.com/content_media/lessons/browsercore/web_page_with_images/food_love_happiness.png
If I used an absolute URL, as in this tag from Figure 2:
<img src="http://coredogs.com/content_media/lessons/clientcore/web_page_with_images/food_love_happiness.png">
then the page would be broken. I would have to fix the HTML. No problem for one page, but CoreDogs has hundreds of pages. Ack!
But if I has used a relative URL, like this tag from Figure 1:
<img src="food_love_happiness.png">
I wouldn’t need to change anything, as long as the image file was still in the same directory as the HTML file.
That’s why Webers almost always use relative URLs. They can move files around, without breaking things.
We’ll talk more about relative and absolute tags in the next lesson.
alt attributesrc is the most important <img> attribute but there are others. One is the alt attribute, which you should add to every image. It gives a text alternative to the tag when the image can’t be shown. The alt tag should describe the image.
The alt attribute is used by screen readers. That’s software used by visually impaired people. As you might guess from the name, screen readers read out the text of a Web page. If the alt attribute is empty, visually impaired users will not know what the image shows. This is particularly important for informational images.
You should use the alt tag for two reasons. First, federal government Web sites in the US must use the alt tag to comply with the section 508 amendment to the Rehabilitation Act of 1973.
Second, pages containing <img> tags without alt attributes do not validate, that is, they don’t comply with the HTML 4.01 standard we use in CoreDogs. If you read about the img tag in the HTML 4.01 standard, you’ll see this:
User agents must render alternate text when they cannot support images, they cannot support a certain image type or when they are configured not to display images.
“User agents” are usually browsers, though there can be more exotic things. Anyway, you can see that the alt tag is required.
Why would you care about this? Because search engines prefer pages that validate. And that makes your pages easier to find.
You created a drawing in a previous exercise. Now create an HTML page that shows the image. Use a relative URL.
Upload the image and your HTML page to your server. Put the URL of the page below.
(Log in to enter your solution to this exercise.)
<img> tag to show images. alt attribute to give a text alternative for each image.Now you know how to show an image on a page. Let’s see how you can style image boundaries, like add a color border.
You know how computers represent images. You know how to find free images, and show them on page. Let’s use CSS to add some styling to image boundaries.
By the end of this lesson/page, you should:
As you know, the <p> tag puts white space around text. For example:
<p>This is a paragraph.</p>
<p>This is a not a paragraph. Oh, wait, yes it is.</p>
Without styling, this looks like:

Figure 1. Paragraphs
There is white space above, below, and to the left and right of each paragraph. But how does the browser decide how much white space?
Let me ask another question. Why is the text in Figure 1 black? You learned that it’s black because that is the browser’s default, when you don’t use a style. Why is the background white? Same reason. Why use a serif typeface? Same reason.
So, how does the browser decide how much white space to use around <p>s? Same way. The browser has defaults that it uses, unless you tell it otherwise.
Each block tag, like <p> and <hx>, is inside a box. The box has a border (usually invisible) and white space. You control the box by using the CSS attributes border, margin, and padding.
The box model defines how box around a block tag is created. Let’s look at it.
Let’s start with the most fun part, the border.
border attributeYou have lots of control over the border around an element.
Here’s a picture of me in the snow, with a solid border.
Here’s the code:
.solid_border {
border-style: solid;
}
...
<img class="solid_border" src="kieran_snow.jpg">
Here’s a dashed border:
Here’s the code:
.solid_border {
border-style: dashed;
}
The default style is hidden.
There are more styles, like dotted and grooved. You can see the list at SitePoint.
There are four borders around the image. You can give each border a different style. For example:
Here’s the code:
.mixed_border {
border-top-style: solid;
border-right-style: hidden;
border-bottom-style: groove;
border-left-style: dotted;
}
It looks terrible, but it shows you the options.
You can put the values on one line, like this:
.mixed_border {
border-style: solid hidden groove dotted;
}
How does the browser know which style to put on each side? It goes in the order top, left, bottom, right. That’s in clockwise order from the top:

Figure 2. Border order
This ordering applies throughout CSS. For padding, margins, and other things we’ll see later.
You can set the width of borders like this:
.thick_border {
border-style: solid;
border-width: 10px;
}
The width won’t show unless you set a style as well.
Set a border color using the usual color codes, the same ones used for fonts and everything else. For example:
.color_border {
border-style: solid;
border-width: 10px;
border-color: #668014;
}
Usually when I set colors, I specify color, style, and width, and want them the same for all sides. There’s a shortcut for that:
.color_border {
border: solid 10px #668014;
}
This is what I normally do for borders. Put all the options in a single border style. Simple is Good.
We’re talking about the box model. We’ve talked about borders. Another attribute, margin, let’s you control the spacing around an element.
Suppose I had this HTML:
<p> <img src="kieran_snow.jpg"> <img src="kieran_snow.jpg"> <img src="kieran_snow.jpg"><br> <img src="kieran_snow.jpg"> <img src="kieran_snow.jpg"> <img src="kieran_snow.jpg"><br> <img src="kieran_snow.jpg"> <img src="kieran_snow.jpg"> <img src="kieran_snow.jpg"> </p>
Figure 3. Dog matrix code
It renders like this:

Figure 4. Dog matrix
The gap between the images is because of the white space characters in the HTML: the spaces and new line between each imate.
I’ll change one of the lines to this:
<img class="big_margin" src="kieran_snow.jpg">
Now I’ll add a class:
.big_margin {
margin: 20px;
border: dotted 2px #668014;
}
Here’s what I end up with:

Figure 5. Dog matrix with margin
Notice how there’s space between the border and the other elements around the image. That’s what the margin property does.
The padding property also adds a gap, but it’s a little different. Here’s a style:
.big_padding {
padding: 20px;
border: dotted 2px #668014;
}

Figure 6. Dog matrix with padding
The padding attribute adds a gap between the edge of the content and the border. That’s different from margin, which adds the space outside the border.
You can use them both together.
.big_margin_padding {
margin: 20px;
padding: 20px;
border: dotted 2px #668014;
}
It looks like:

Figure 6. Dog matrix with margin and padding
You can use the same properties with text. For example, let’s say you want to make a message stand out, like this:

Figure 7. Text standing out
Here’s a page that does 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>The Dog Zone</title>
<style type="text/css">
body {
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-size: 14px;
}
.stand_out {
border: dotted 2px red;
background-color: #FFB6C1;
font-weight: bold;
font-style:italic;
margin: 20px;
padding: 20px;
}
</style>
</head>
<body>
<h1>The Dog Zone</h1>
<p>Welcome to the best place for dog fun on the Web.</p>
<p class="stand_out">Today only! 50% off road kill!</p>
<p>Get your stuff here!</p>
</body>
</html>
You can try the page, if you like.
Browsers render elements with defaults for border, margin, and padding. For instance, the default border is hidden, meaning no border is visible. You can change them all with CSS.
Another neat thing you can do with images is use them as backgrounds, for entire pages, or for individual elements. Let’s see how.
You know how to add images to a page, and put boundaries around them. Let’s see how you can put images into the background of a page.
Background images can give a nice look to your pages. Usually they’re used to set a mood. Backgrounds can be set for entire pages, or for parts of pages.
By the end of this page, you should:
You can use one large image to set a mood, as seen on this page. This might a page on a landscaping site, or one about nature vacations. The image has a relaxed, natural feel.
I didn’t want the image to interfere with the text, so I put it in the upper right of the page, and made it fade out fairly quickly.
Let’s see how I created the effect. I started with a larger version of this photo I took at a local park:
![]()
Figure 1. Scenery
I used Gimp to add a transparency mask, a black-and-white overlay that tells Gimp what part of the image shows through. You can see how it works:

Figure 2. Transparency mask
You can see the mask to the right of the photo. Imagine that it’s dropped on top of the photo. White areas in the mask let the photo show. Black areas block the photo from showing. When the photo is blocked, the background underneath shows. It’s a simple white background in this case, but it could be another color, a texture, a different photo, ... whatever your imagination can conjure.
The mask uses a gradient, that is, the mask’s color gradually changes from white to black. When there are gray pixels in the mask, Gimp combines the color from the photo with the background layer’s color. The more white there is, the more of the photo’s color is used.
Here’s a small version of the result:
![]()
Figure 3. Background image
You don’t have to know how to do photo work like this yourself, if you have someone to do it for you. But it helps to know in general terms how graphics people do their work. Using transparency masks is a common technique.
Now that I have the image, I want to put it in the upper right of the page. Here’s the entire 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>Full image background</title>
<style type="text/css">
body {
background-image: url('scenery_back.jpg');
background-repeat:no-repeat;
background-position:top right;
}
</style>
</head>
<body>
<h1>Full image background</h1>
<p>This is a sample page with a background image.</p>
</body>
</html>
Figure 4. Page with a background image
Notice that the image is added in the CSS, not in the HTML. Because the rule is attached to the body, the image will be behind the entire page.
The first part of the rule tells the browser where the image is:
background-image: url('scenery_back.jpg');
The browser looks for the image in the same directory as the style sheet. The next lesson explains how to make URLs point to different places.
The image file I made is 640 pixels wide and 480 pixels high. Your computer’s display is bigger than that, maybe 1024 pixels wide and 768 pixels high. What happens?
By default, the browser repeats the background image until it fills up the entire display. I just wanted one copy of the image. So, I added this to the CSS:
background-repeat:no-repeat;
Finally, I wanted the image at the top right of the page. Hence the rule:
background-position:top right;
Sometimes you want a page to look like it was written on paper, chiseled in stone, printed in the sky, or whatever. Have a look at the Make ‘em proud theme. The background image is yellow with dark flecks, giving the impression of old paper.
This type of effect uses a tile. A tile is a small graphic that looks good when it’s repeated. The edges fit together seamlessly.
Here’s a tile from GRSites.com:

Figure 5. Background tile
Here’s what it looks like when used as a background:
Hi there!
This is a tiled background. Notice how the edges of the tile are seamless?
There are a bazillion seamless tiles you can use for free, or you can make your own.
We now return you to your regular background.
Figure 6. Using the tile
The CSS rule is something like:
.tiled {
font-size: 20px;
color: white;
padding: 20px;
background-image: url('tile.gif');
}
Figure 7. CSS rule for tiled background
There is no background-repeat style. The browser’s default is to repeat across and down the tiled area, filling it completely. This is what we want.
Some tiles use part of the image to represent specific objects. They can be a bit tricky to use well, but give nice results.
This example uses another background from GRSites.com:
Hi there!
This is another tiled background. The edges are seamless as well.
The <p>s on top of the background have some extra padding on the left. This looks like the text was indented a bit to avoid the left margin.
We now return you to your regular background.
Figure 8. Using the tile
A rule for this would look something like:
.notepaper {
font-size: 16px;
color: black;
padding: 20px 20px 20px 100px;
background-image: url('paper_background.gif');
background-repeat: repeat-y;
}
Figure 9. CSS rule for notepaper background
The padding style uses the same ordering shorthand we saw earlier: clockwise from the top (top – right – bottom – left). The background-repeat is set to repeat-y. This repeats the image down the page, but not across.
To see what this means, I’ve taken another paper background image from GRSites.com. Please have a look.
The image is 800 pixels wide. That’s not as wide as most displays these days, which start around 1,024 pixels. So what does the browser do when with it runs out of background image?
To see what it does, I’ve cropped the background image to 300 pixels:

Figure 10. Cropped tile
(I added the border so you could see how big the image is.)
Here’s what it looks like without any control over the repeating:
Hi there!
This is another tiled background.
It's been cropped to 300px wide.
We now return you to your regular background.
Figure 11. Using the cropped tile
Remember, the browser’s default action is to repeat background images. This tile is designed to repeat in the y direction (down the page), but not in the x direction (across the page). So I need to add background-repeat:repeat-y; to the CSS rule, so that it only repeats down the page, but not across. Here’s the rule:
.notepaper {
font-size: 16px;
color: black;
padding: 20px 20px 20px 100px;
background-image: url('paper_background4_cropped.gif');
background-repeat: repeat-y;
}
Figure 12. CSS rule for with background-repeat:repeat-y;
Here’s the result:
Hi there!
This is another tiled background.
It's been cropped to 300px wide.
This time, I've used background-repeat:repeat-y; in the CSS rule. Hooray!
We now return you to your regular background.
Figure 13. Using the cropped tile with background-repeat:repeat-y;
Ahhhh… Much better.
On this page, you learned how to add background images to a page. You learned how to add a single image, and tiles. You learned how to use background-repeat:repeat-y; for tiles that are designed to repeat vertically only.
We’re getting close to the end of the lesson. The next lesson starts putting everything together to let you create entire Web sites.
But we want to be able to do some cool, Web 2.0 stuff with images. Let’s use jQuery to mess with images.
W00f!
You need to create the right look and feel for your Web site. You learned about typography. Now let’s talk about color.
These ideas apply to both text and images. Text color is set with CSS. Image color is part of the images themselves.
By the end of this page, you should:
Our goal is to create a color scheme for a Web site. A scheme is a set of a few colors. It’s often called a palette.
Here are some samples:

Figure 1. Color schemes
These color schemes are from Colors on the Web, a site that has schemes, a color wheel, a contrast analyzer, and other things.
We want a scheme that is usable and aesthetically pleasing.
This page is not about CSS. It’s about color. But eventually, you’ll need to make your color choices into something you can use in CSS.
Recall that colors in CSS are usually represented as three numbers: the amount of red, green, and blue that make up a color. Each number is from 0 to 255. You can set colors using the three numbers, like this:
color: rgb(128, 0, 0);
Or you can use a hexadecimal value:
color: #800000;
rgb(128, 0, 0) and #800000 are different ways of saying the same thing. Use whichever is more convenient. For example, the schemes from Colors on the Web in Figure 1 give you hexadecimal numbers. To use one of them, copy-and-paste the hexadecimal numbers.
This page will help you create a GECS, a Good Enough Color Scheme. It may not win any art awards, but it won’t embarrass you, either.
Before I show you how to make a GECS, we need to have some good words for talking about colors. RGB codes are fine for computers, but that’s not the way people think about about color.
Let’s start by finding good ways to talk about:
When you’re working with a client on a Web site’s colors, talking about RGB codes won’t get you very far. But you can use words like “intense blue,” “bright green,” and “washed out orange.” Let’s see if we can come up with some ways of talking about colors that are precise, but also make sense to regular people.
HSV is an alternative to RGB. As in RGB, a color is specified by three numbers. But the numbers mean different things. They mean Hue, Saturation, and Value.
Hue is what we normally mean by “color.” Red, green, orange, violet, ... they are hues. The color wheel captures them. Here is a color wheel:

Figure 2. Color wheel
There are many different kinds of color wheels. This one is the color wheel that GIMP uses. The primary hues – red, green, and blue – are as far apart as they can get on the wheel.

Figure 3. Primary hues
As you move around the wheel, from one primary hue to another, you start mixing hues:

Figure 4. Mixing hues
When you have an equal amount of two primary hues, you get a secondary hue, like yellow, that looks entirely different from both of the primaries:

Figure 5. Secondary hue
So the fir