ClientCore

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.

A Web page with text

Where are we?

The foundations book explained how browsers use HTTP to get HTML files from servers. Let’s open up those files and look inside.

This chapter’s goals

By the end of this chapter, you should:

Let’s get started.

The structure of a Web page

This lesson’s goals

By the end of this lesson, you should know:

  • The structure of a Web page.
  • What character sets are.
  • Indenting, which makes it easier to change a page.
  • Why it’s important to get the title right.

A template

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.

Exercise: Upload the template

Upload the code in Figure 1 to your server. I’ll lead you through it this time.

We’ll do the following:

  • Make a file on your computer, with the template code from Figure 1 in it.
  • Upload the file to your server.
  • Look at the result in your browser.

Making the file

On your computer, create a new directory for each exercise. For example, within your My documents directory, you might create a directory called coredogs.

Creating a directory

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:

Directories

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:

Figure toolbar

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

Copying to the clipboard

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.

Upload your file

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:

Connecting to your server

You’ll see a split screen, like this:

FTP split screen

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:

Create directory button

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

Create directory dialog

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:

Local drives and such

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

Local directory

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

FTP split screen

You should see your file on the server. W00f!

CC
CC

Wow, that’s a lot to go through to upload a file.

Kieran
Kieran

True. But after a while it gets to be second nature. You won’t even think about it.

CC
CC

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.

Kieran
Kieran

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:

  • Large step - Connect to the server
    • Small step - Start WinSCP
    • Small step - Use the connect dialog
      • Tiny step - Type in the server name
      • Tiny step - Type in the user name
      • Tiny step - Type in the password
      • Tiny step - Select FTP
      • Tiny step - Click the Login button
  • Large step - Upload the file
    • Small step - Find the file to upload in the left window
    • ...
CC
CC

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?

Kieran
Kieran

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?

  • Someone who needed a new set of instructions every time something changed.
  • Someone who could adapt to changes him- or herself, because s/he knows why the small steps are done.

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.

Look at the file in your browser

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:

Template displayed

W00f! W00f! W00fy-w00f-w00f! With w00f sauce!

Later, if you forget the basics of creating and uploading a page, come back to this exercise.

Enter the URL of your page as your solution to this exercise.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Nesting

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.

Tag nesting

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.

Indenting

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

Indenting

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.

Renata
Renata

If it looks the same to the user, why would it matter? In the end, it’s the user experience that’s key.

CC
CC

Can I answer that one?

Kieran
Kieran

Sure.

CC
CC

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.

DOCTYPE

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.

The <head> section

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

Character set

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:”

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.

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

Page title

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:

Buffy page

Figure 6. Buffy search

I went to the page, and saw this in the browser’s title area:

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

A broken page

While researching this lesson, I came across some interesting code. I saw the following in Google:

Google listing

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:

Broken title

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.

The body

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.

Renata
Renata

Say I’m looking at a Web page. Can I check out the HTML behind it?

Kieran
Kieran

Yes, you can. In Firefox, press Ctrl-U (Windows) or Cmd-U (Mac). Or in the menu, View | Page source:

View | Page source

Try it. Bring up the template page in your browser. Now look at the page source. Compare it with Figure 1.

Summary

You learned about:

  • The structure of a Web page.
  • What character sets are.
  • Indenting, which makes it easier to change a page.
  • Why it’s important to get the title right.

What now?

Let’s start adding some HTML tags to the body.

Patterns

This lesson’s goals

By the end of this lesson, you should know:

  • What patterns are.
  • How patterns make your life easier.

What’s a pattern

Some situations come up again and again. For example, a bunch of people need to make a choice. Eat all the dog food now, or save some for later? Which movie should we watch? Pirates or ninjas?

Pirates or ninjas?

Figure 1. Pirates or ninjas?

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

Direct voting

Figure 2. Direct voting

This is a pattern, that is, a common way of solving a common problem. We could describe the pattern like this:

Goal: Group decision

Pattern: Direct voting

Works well: When there are a few voters.

Another pattern is to have the people elect representatives. The representatives make the choice on behalf of everyone.

Representative voting

Figure 3. Representative voting

The pattern is:

Goal: Group decision

Pattern: Representative voting

Works well: When there are many voters.

So direct voting and representative voting are common ways of solving a common problem. They’re useful in different situations. One is better when there are just a few voters. One is better when there are lots of voters.

Web patterns

There are patterns for Web sites, too. Suppose an organization called Public Opinion hires you to:

Make a Web site about the pirates versus ninjas debate. It will have four pages. The first one will be the home page, telling people what the site is for. There’ll be a page about pirates. There’ll be another page about ninjas. And the last page will let people vote.

We want everyone to know that Public Opinion owns the site. And that each page is copyrighted.

Also, make it easy for people to get from one page to another.

How do you get started? One way is to look at the goals, and think about patterns. For example, how to let everyone know that its Public Opinion’s site? One way is with a header on every page, like this:

Header pattern

Figure 4. Header pattern

People are used to this pattern. A lot of Web sites use it, including CoreDogs. The pattern is a solution to a common problem: tell people what a site is and who owns it.

Another goal is to tell people that each page is copyrighted. A common pattern for that is to put a copyright notice in the footer of every page:

Footer pattern

Figure 5. Footer pattern

Again, we have a common solution to a common problem. How to show a copyright statement? Put it in the footer of every page. Lots of sites do this. Including CoreDogs.

Now, how about this goal: “make it easy for people to get from one page to another.” A common pattern is the nav bar, short for navigation bar. You’ve seen lots of these:

Horizontal nav bar pattern

Figure 6. Horizontal nav bar pattern

Vertical nav bar pattern

Figure 7. Vertical nav bar pattern

Either one would work.

You’ll learn how to make all of these pieces in CoreDogs. Put the pieces together, and you have an entire design:

Complete page design

Figure 8. Complete page design

Patterns rule!

Patterns let you do Web work more quickly. You don’t have to relearn all of the time. You learn how to make a nav bar once, and you can use the pattern on site after site.

Patterns make it easier to design sites. You don’t have to think up new solutions to the problem of letting people jump from page to page easily. You already know that nav bars will do this. You can say to yourself, “Self, I’ll put a horizontal nav bar in here,” and leave the details for later.

Patterns make it easier for Web workers to talk to each other. Say “horizontal nav bar,” and every Web designer will know what you mean.

The CoreDogs pattern library

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:

Tools tab

Patterns tab

Figure 9. Accessing the pattern library

Here’s your first pattern. It’s the template from the previous lesson.

<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>TITLE</title>
  </head>
  <body>
    BODY
  </body>
</html>

Figure 10. Standard page template (again)

To make a simple Web page, begin with this pattern. Copy-and-paste the code into your editor, and get started.

Notice that this template has several different tags in it: <html>, <head>, <body>, and others. Individual HTML tags aren’t very useful by themselves. It’s when tags are combined into patterns that they start to do useful work.

You saw this just above:

It tells you that a pattern for what you just read about is in the pattern library. In this case, the code in Figure 10 is in the library.

Remember: patterns are your friends.

Summary

You learned about:

  • The structure of a Web page.
  • What character sets are.
  • Indenting, which makes it easier to change a page.
  • Why it’s important to get the title right.
  • What patterns are.
  • Patterns make your life easier.

What now?

Let’s start adding some HTML tags to the body.

Basic HTML tags

Where are we?

On the previous page, you uploaded a standard template for a Web page. Let’s add some tags to it.

Headings and paragraphs

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:

Heading tags

Figure 1. Heading tags

CC
CC

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>

Kieran
Kieran

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:

Article outline

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>

CC
CC

Oh, OK, I get it. The numbers are whether it’s a heading, a subheading, a subsubheading, and so on.

Kieran
Kieran

Right!

So, headings separate sections of content. Most sections contain paragraphs. A paragraph is some text with white space before and after it. You’re reading a paragraph now.

Paragraphs are created with the <p></p> tag.

Here’s a page using heading and paragraph tags.

<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Building a Dog House</title>
  </head>
  <body>
    <h1>Building a Dog House</h1>

    <p>Building a dog house is easier if you work out what you are doing ahead of time. This page will help you with the process.</p>

    <h2>Find a plan</h2>

    <p>The first step is to find a plan for the dog house. There are many plans on the Web. But you need to choose carefully.</p>

    <h2>Buy the materials</h2>

    <p>Buy the wood, fasteners (nail, screws, etc.), paint, and whatever the plan calls for.</p>

  </body>
</html>

Figure 2. Page using headings and paragraphs

You can show the page in your browser.

An <h1> is used to show the user the name of the page. This is the same as the <title> on this page, but isn’t always. For example, the page you’re reading now has <h1>Basic HTML tags</h1> for the user, but <title>Basic HTML tags | CoreDogs</title> for the browser title and search engines. This page’s title is the heading with the site name appended to it.

“Appended” means “added to the end.”

On the dog house page, <h2> is used to start the major sections of the page. You don’t have to use heading tags this way. The browser doesn’t know anything about sections and subsections. You tell it to show a heading, and it will do so. You could have HTML like this.

<h5>Building a Dog House</h5>

<h1>Building a dog house is easier if you work out what you are doing ahead of time. This page will help you with the process.</h1>

<h3>Find a plan</h3>

<h2>The first step is to find a plan for the dog house. There are many plans on the Web. But you need to choose carefully.</h2>

Figure 3. Strange headings

The browser will do exactly what you tell it to, but it would look strange to the user.

Exercise: Try the strange headings

Create a Web page using the markup in Figure 2, but change it to use the markup in Figure 3. What do you think of the result?

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Renata
Renata

A question.

Kieran
Kieran

Yes?

Renata
Renata

Do you use <h1> and <p> in CoreDogs?

Kieran
Kieran

Yes. If you look at the source code for this page, you’ll see them.

Renata
Renata

OK. But the fonts on the dog house page look nothing like the fonts on this page. How can they be the same tags?

Kieran
Kieran

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.

Line breaks

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.

Exercise: Break tags on the same line

Create a page with the markup in Figure 4. Put the markup for the limerick all on one line, like this:

<p>There once was a Porter named Jim,<br>Whose voice filled the church to the brim.<br>But his

How does it look in a browser? Is it any different from my page?

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Indenting

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.

Add horizontal lines

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>&copy; 2010, CoreDogs.</p>

Figure 6. The <hr> tag

You can see it in action.

HTML entities

There’s something strange in Figure 6. What’s that &copy; thing in line 2?

This is called an HTML entity. It’s a code for a special character of some sort. For example, &copy; 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 &lt;p&gt; tag renders a paragraph.</p>

&lt; renders as <, and &gt; renders as >. Now the content will look right.

Another useful entity is &nbsp;. 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 &nbsp; when you want several spaces. This:

<p>Mostly&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;harmless</p>

will show as:

Mostly      harmless

Wikipedia has a list of HTML entities.

Summary

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.

What now?

Let’s look at some tags you can use to do simple font work.

Simple font tags

Where are we?

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.

Strong

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.

Emphasized

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.

Exercise: How many dogs does it take ...

Create a page that looks something like this when rendered.

Result

When you have finished, compare the HTML source code of my solution with yours. Look at the way my HTML is laid out, especially the indenting.

Upload your solution to your server, and enter the URL below.

[solution]You can try my solution

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

In this lesson, we talked about basic font manipulation with <strong> and <em>.

What now?

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.

Adding style with CSS

Where are we?

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.

This lesson’s goals

By the end of this lesson, you should:

  • Understand the elements of font styling.
  • Be able to style text.
  • Be able to change background colors.
  • Know how typography affects the mood of text.

Elements of fonts

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

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:

Typefaces

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:

Serif typeface

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:

Sans serif typeface

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

Fixed vs. 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.

Serif typeface

Figure 2 (again). Serif typeface

There are also “cursive” and “fantasy” typefaces. Here are some examples.

Cursive and fantasy typefaces

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.

Size

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

Weight refers to how bold the font is. Most people stick to two choices: bold and normal.

Variations

There are other font variations. Some people like to use small caps for headings:

Small caps

Figure 6. Small caps

Color

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:

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

Styling fonts

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:

Page rendered

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:

Styled page rendered

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

Renata
Renata

All of the style rules are inside these lines:

<style type="text/css">
...
</style>

Do I have to include those?

Kieran
Kieran

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.

Exercise: Style a joke

Make a page that looks like this:

Styled dog joke

Hints:

  • I used the color gold from the color chart.
  • I used only <h1> and <p> in the <body>.
  • I defined a class called attribution for the last line.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Font types in CSS

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 bolder and lighter.

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.

Text alignment

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!

Exercise: Report template

Make a Web page that’s a template for company reports. Here’s a screenshot (made narrow to fit):

Report template

Figure 1. Report template

The typeface is Verdana. The color for the background is #FFFFCC. The heading colors are #660000 and #006600. The font is 14px high.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Aesthetics

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.

Font moods

Figure 12. Font moods

You can see which fonts match which events.

Going deeper

  • Text spacing in CSS. This article explains how to control the whitespace around letters, words, and lines.
  • Safe typefaces. This article lists typefaces that are available on Windows, Macs, and Linux machines. It explains that you can create graphics to include unusual fonts in your Web pages.

Summary

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.

What now?

There are a lot of options with CSS. You can do almost anything!

Too much information!

Renata
Renata

I’m feeling overwhelmed here.

CC
CC

Me, too. There are so many choices!

Kieran
Kieran

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.

  • Use a 14px font for most text.
  • Use larger fonts for headings.
  • Use smaller fonts for support text, like help messages.
  • Use a sans serif typeface for everything.
  • Left-align everything.

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.

What now?

This lesson gave you some useful guidelines. Hmm. Maybe we should remember them.

Patterns again

Where are we?

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.

This lesson’s goals

Let’s talk a little more about patterns.

Patterns

Kieran
Kieran

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?

Renata
Renata

Yes, very.

Kieran
Kieran

Why?

Renata
Renata

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.

Kieran
Kieran

Where did I get those rules?

Renata
Renata

You said that you’d used them in the past, that they worked for you.

Kieran
Kieran

Right!

Remember that a pattern is a way of solving a problem that someone has found useful. Instead of working out the solution to a problem all over again, sometimes you can just grab a pattern than works.

CoreDogs has a pattern library. To get to it, click on the Tools tab, and then the Patterns tab:

Tools tab

Patterns tab

Figure 1. Accessing the pattern library

Look at the Basic text styling pattern. It uses the guidelines from the previous lesson. The pattern includes helpful tips, like using quotes around typefaces that have spaces in their names.

Also look at the Title – Details pattern. It tells you how to use section headings. The pattern uses CSS margins. We haven’t covered that yet; that comes later. But you should be able to follow the pattern.

Some patterns are often used together, or are alternatives to each other. Both of the patterns just mentioned link to each other in Related patterns.

Related patterns

Figure 2. Related patterns

Adjusting patterns

CC
CC

Patterns are shortcuts, right?

Kieran
Kieran

Yes.

CC
CC

But is using someone else’s shortcut always a good idea? It might not do exactly what you want.

Kieran
Kieran

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.

Title text and detail text are the same color

Figure 3. Title text and detail text are the same color

But maybe you want different colors.

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

New colors

Figure 4. New colors

So you need to adjust the pattern.

What this means is that you can’t just throw the pattern in without understanding it. You need to understand it, so you can change it to fit the job.

Patterns are not like Lego bricks that you can snap together. They’re more like cookie cutters.

Cookier cutter

Figure 5. A cookie cutter

Image from WikiHow.

You can just stamp out the basic shape. But if you need to, you change the shape before you put the cookie into the oven. Maybe trim off the edges of the hat, and round out the head.

Original cookie shape Trimmed cookie shape

Figure 6. Original and changed cookie

Adjust patterns as you need to, to fit the goals of your project.

Other pattern libraries

The CoreDogs pattern library was created to help you learn Web tech. The patterns are basic, and easy to use.

Professional Webers might prefer other libraries. The Yahoo pattern library is an example.

Summary

  • A pattern is a proven way of solving a problem.
  • Reusing good patterns makes it easier and faster to create a good Web site.
  • CoreDogs has a useful collection of patterns.
  • You need to understand how each pattern works, so you can adjust it as needed.

What now?

Let’s see how you make lists of stuff.

Making lists

Where are we?

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

Unordered lists look like this:

  • An item
  • Another item
  • Yet another item

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.

Exercise: Unordered list of dog breeds

Find a list of dog breeds on the Web. Create a Web page with a list of five of your favorites. List them alphabetically.

Upload your page to your server, and add a link below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Ordered lists

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:

  1. An item
  2. Another item
  3. Yet another item

Exercise: Ordered list of dog breeds

Find a list of dog breeds on the Web. Create a Web page with a list of five of your favorites. List them in your order of preference: favorite first, next favorite second, etc.

Upload your page to your server, and add a link below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Nested lists

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:

  • 19th century
    • 1836: Eunice (mastiff) crowned Bitch of New South Wales.
    • 1840:
      1. Isaac (lab) eats 15 pounds of figs at Moreton Bay.
      2. Thark (sheltie) barks for 17 hours nonstop. Riots in Port Jackson.
    • 1895: Booblo (Welsh terrier) marks Barton as future PM.
  • 20th century
    • 1915: Groft (border collie) rescues sausages under fire.
    • 1967: Lilabeth (portuguese water dog) directs shark to prime ministerial snack.
    • 1975:
      1. Goofer (collie) bites PM.
      2. Goofer (collie) bites PM again.
      3. Kerr (govenor general) bites PM.
      4. Goofer (collie) becomes PM.

Figure 4. Rendered nested lists

Notice that:

  • Lists can be nested to any depth.
  • Ordered lists can be nested inside unordered lists. The reverse is also true; unordered lists can be nested inside ordered lists.
  • Inner lists are completely contained within <li> tags of outer lists.
  • The indenting is essential in figuring this out. Not for the computer, but for a person trying to update the list.

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

Exercise: Styling lists

Make a page like this:

Styling lists

The background color of the page is #FFFFEE. The silly text is #FF1493. The silly typeface is Comic Sans MS. The rest of the page is Arial. The base text size for the body is 14 pixels.

Hint: create two different classes for the <ul> tag, plus a rule for the <body> tag.

Upload your page to your server, and add a link below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

List bullets

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

Exercise: Styling lists again

Make a page like this:

Styling lists

The bullet in the silly list is different.

Upload your page to your server, and add a link below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Going deeper

SitePoint has a nice CSS list reference page, if you want to know more about styling lists.

Summary

In this lesson, you learned:

  • The basic structure of an HTML page.
  • A set of basic HTML tags, including headings, paragraphs, emphasis, and lists.
  • How HTML entities can be used for special symbols (like ©) as well as to show HTML code.
  • The importance of correct indenting in helping Webers do their work accurately.
  • How to use CSS to style fonts and change list bullets.

What now?

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.

Writing for the Web

Where are we?

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.

This lesson’s goals

By the end of this lesson, you should:

  • Know that you are writing for site users and owners, but the users come first.
  • Know some guidelines for writing for the Web.

The Web is text (mostly)

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:

[amazon 0123694868 full]
[amazon 0321344758 full]

Who are you writing for?

You’re writing for two stakeholders:

  • Site users
  • Site owners

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.

A passel of guidelines

Here are some guidelines for writing Web text.

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

Active voice

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.

Less happy talk

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:

CoreDogs home page happy talk

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.

Eliminate instructions

Here’s the search field on this page:

Search form

Figure 2. Search form

You know how to use this. No instructions needed.

The tree menus:

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:

Public widget

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 for scanning

Write so users can quickly look over the page, without having to read it all.

  • Start a long page with a short summary.
  • Put stuff people look for most often at the top of the page.
  • Use section headings. Make them different from normal text. Change the font size, weight, color, etc. Think about having a table of contents for a long page.
  • Make links look like links. Underlining is good. Don’t underline anything but links.

Use lists

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:

  • Blue thing.
  • Red thing – way cool!
  • Brown thing.
  • Green thing.

Sans serif

Use it. People like it better.

Color contrast

Make the text color easy to read on the background color.

Text size

Older people have trouble with small font sizes. I use 14px as a rule. Larger for headings, of course.

Going deeper

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.

Summary

You are writing for site users and owners, but the users come first.

Guidelines for Web writing:

  • Less text
  • Active voice
  • Less happy talk
  • Eliminate instructions
  • Write for scanning
  • Use lists
  • Sans serif
  • Color contrast
  • Text size

What now?

Time to work on your eMe site.

eMe: Some text pages

Where are we?

You’ve learned some text tags, and a little about styling. You know how to make lists. You’ve read about writing for the Web.

Pages about stuff

Earlier, you thought about stuff you would put on your Web site. Time to make some pages. Create at least two.

If you can’t think of anything, write some pages about yourself. One about your history. Where you were born, schools you went to, like that. The second page could be about your interests. Hobbies, music you like, games you like, etc.

Create a few more pages, if you want. Go over your list of interesting stuff.

Styling

All the pages should use the same style rules. Pick a typeface you like, colors, and so on. You can start with the basic text styling pattern, or start from scratch. Mess around, and find something you like.

External style sheets

Say you make four pages. They all have the same styles. One way to do this is to get the style right on one page, then copy-and-paste the <style> section into the other pages.

The problem is this: what if you decide to change the styles? Suppose you set the background color of all the pages to #FFFFC0, a brightish yellow. Then you decide you like #FFFFEE better. It’s a very pale yellow. You would have to open every HTML file, and make the same change. It would be easy to make a mistake.

You’ll learn more about color codes later.

There’s a better way:

  • Create a separate file that contains only CSS styles.
  • In all the HTML files, add a link to the CSS file.

For example, suppose I had this page. Here is the code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>A page</title>
    <style type="text/css">
      body {
        background-color: black;
        font-family: Arial, Helvetica, sans-serif;
        font-size: 16px;
        color: #FEFEF2;
      }
      h1 {
        color: #FFD700;
      }
      </style>
  </head>
  <body>
    <h1>A page</h1>
    <p>This is a page.</p>
  </body>
</html>

Figure 1. A page

The first thing I do is remove all the CSS rules, and put them in a separate file. I’ll call the file styles.css, though I could call it whatever I like. Usually I give the file a .css extension, though I don’t have to. I’ll put the file in the same directory as the page.

I could put it in another directory. We’ll see that later.

Here is styles.css:

body {
  background-color: black;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 16px;
  color: #FEFEF2;
}
h1 {
  color: #FFD700;
}

Figure 2. styles.css

Notice that the <style> tag isn’t there. It’s HTML, and does not belong in the file.

Now, I delete the <style> section from page.html, and replace it with this:

<link rel="stylesheet" type="text/css" href="styles.css">

I put the name of the file I just created in the href attribute. Don’t forget the extension.

Here’s what the HTML file looks like now.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>A page</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
  </head>
  <body>
    <h1>A page</h1>
    <p>This is a page.</p>
  </body>
</html>

Figure 3. HTML file with external style sheet

The page will look the same as before. Have a look.

Reusing the style sheet

I can use this line in as many files as I like:

<link rel="stylesheet" type="text/css" href="styles.css">

I could have a hundred pages using the styles, if I want.

The <body>’s background color is black. You can see that in line 2 of styles.css:

background-color: black;

Suppose I want the background on all pages to be dark gray. I change this one line in styles.css:

background-color: #404040;

Every file that links to styles.css will change. If that’s 100 pages, then 100 pages change. W00f!

eMe: Text pages with external styles

Write some pages about something on your interesting stuff list. Create at least two, but more if you like.

Make sure all the pages use the same style rules. Use an external style sheet. You can put all the files in the same directory.

Upload your files to your server. Put the URLs of the files below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

  • Using an external style sheet lets you change many pages at once.

What now?

Time for some more exercises.

Exercises: A Web page with text

You should do the four recommended exercises. Do the optional exercises if you want more practice.

Exercises in the Explore section are more challenging. You may need to use HTML and CSS we haven’t covered yet. Get ready to Google!

Recommended

Exercise: Product description

Create a page that looks like this, using CSS styles:

Solution

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Cats and dogs

Create a page that looks like this, using CSS styles:

Cats and dogs

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Metaphor

Create a page that looks like this, using CSS styles:

Metaphor

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Bar jokes

Create a page that looks like this, using CSS styles:

Bar jokes

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Optional

Exercise: Studying advice

Create a page that looks like this:

Study tips

Match the colors approximately. Use any sans serif font. Use at least one CSS class (I used more in my solution).

I made my browser narrow to make the screenshot above, so I could fit it in this page. You don’t need to have this width.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Explore

These challenging exercises may use HTML and CSS that you haven’t seen yet. Get ready to Google!

Exercise: Friendly formulas

Make a page that looks like this:

Friendly formulas

Upload your solution to your server. Enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Text shadow

Make a page like this:

Text shadow

Do not use a graphics program! Use HTML and CSS only.

Upload your solution to your server. Enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Backwards text

Make a page like this:

Backwards text

Type the text into your HTML in the normal way! Copy-and-paste this into your solution:

Hey!
This is reversed!
Flip it around, willya, buddy?

Upload your solution to your server. Enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Ticking noise

Make a page showing the YouTube video, “Potter Puppet Pals: The Mysterious Ticking Noise.” Your page should look like this:

Ticking noise

Upload your solution to your server. Enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

A page that interacts

Where are we?

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.

Programming is scary!

This chapter is about programming.

CC
CC

Are you crazy? I can barely balance my check book! I hate all that math stuff!

Kieran
Kieran

Hey, calm down. Breathe, that’s it.

Many people think they can’t do it. But my 20 years of experience says you can learn programming, at least to the level that CoreDogs covers. Which, as programming goes, isn’t a lot.

Some things to remember.

First, how you learn matters. If I threw a bunch o’ tech at you all at once, of course you’d be confused. That’s natural.

Unfortunately, most tech experts don’t have strong teaching skills. They move too fast, cover too much, too quickly. Deep down, some experts think that programming isn’t hard, so learners shouldn’t need help.

They’re wrong. Programming is hard to learn, if you try to learn it from an unskilled teacher, or a poorly written book. Most people can do it. But teachers and authors need to understand how people learn, and respect learners’ experiences.

Let’s take it slowly. In fact, really slowly for someone as anxious as you are, CC. Baby steps.

This chapter is long. The reason? We go slowly. Baby step, baby step, baby step. That might bug you if you already know how to program. Please remember that others are learning this for the first time.

Second, find someone else to learn with. Not an expert, but someone who’s at your level, or a little ahead. If you and your buddy do need expert help, pick someone who is patient.

Third, I want to kill a myth. Programming is not about math. All those sines and cosines you learned to fear? You won’t see them here. No calculus, no factoring, no quadratics.

CC
CC

Really? Promise?

Kieran
Kieran

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?

CC
CC

Well, yes, you got me, I could. I can add and subtract. Even multiply and divide, on a good day.

Kieran
Kieran

Then you’re all set.

The most difficult thing about programming is breaking down a large problem into smaller ones, so you can work on each small one independently. This has nothing to do with math. People who write history books do the same thing. They take big events (e.g., the American Civil War), break them into parts (e.g., The US before the war, The first shot, The south’s initial success, ...), and write a chapter for each one.

Renata
Renata

You’ve spent a lot of time on CC’s anxiety.

Kieran
Kieran

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.

This chapter’s goals

By the end of this chapter, you should:

Let’s get started.

CC
CC

Come on CC, you can do it, girl.

Kieran
Kieran

Yes, you can. And I’ll hold your paw all the way.

What is JavaScript?

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:

  • Empty the old coffee grounds from the coffee maker.
  • Find the container with the new coffee grounds.
  • Put four scoops of coffee grounds into the coffee maker’s basket.
  • Fill the coffee maker with water, to the 12-cup line.
  • Turn the coffee maker on.

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.

Humans and 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.

A sales tax program

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.

Renata
Renata

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.

CC
CC

Try typing in a negative price.

Renata
Renata

That doesn’t make sense.

CC
CC

Exactly. Shouldn’t the computer know that?

Kieran
Kieran

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.

Renata
Renata

How would you do the error checking? I’m just curious.

Kieran
Kieran

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.

CC
CC

So when you write a program, you pretend you’re a Web browser?

Kieran
Kieran

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, ...”

Renata
Renata

So you have to know what instructions they can follow.

Kieran
Kieran

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

CC
CC

Huh. That makes sense.

Kieran
Kieran

Think you’ll be able to write a program?

CC
CC

I don’t know yet.

Kieran
Kieran

Fair enough. We’ll see.

Events

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.

  • When a human wakes up, she makes some coffee.
  • When someone wants to buy something, Xena works out the total price.
  • When someone wants to visit you, they follow your driving instructions.

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.

Summary

  • Your Web browser is like a human. You give it instructions, just like you give instructions to a human.
  • The browser follows instructions, just like a human would.
  • You have to know what instructions the browser can follow. Just like you have to know what language the human speaks.
  • Events are things that happen, like someone clicking a button. You bind programs to events. Events trigger programs.

What now?

In the next lesson, let’s see how you can include JS code on a Web page.

Adding JavaScript and jQuery to a page

This lesson’s goals

In this lesson, you’ll learn how to:

  • Add JavaScript code directly on a page.
  • Add JavaScript code from an external file.
  • Add the jQuery library.

JavaScript and browsers

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:

  • Programs are put directly into Web page.
  • Programs are in separate files. Web pages load the files they want.

Let’s talk about each option.

On-page code

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.

Renata
Renata

What about lines 6 and 8? They look like HTML, with the < and >.

Kieran
Kieran

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.

CC
CC

What about type="text/javascript"? Does that need to be there?

Kieran
Kieran

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.

Renata
Renata

When I tried the page in Figure 1, the message box showed before any content. Like this:

Alert

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

After alert

Is that normal?

Kieran
Kieran

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.

Including a file

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.

Exercise: Change the message

Change the alert() message to “Be kind to your dog.” Upload your solution to your server, and paste the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Add a message

Add a second alert() message, like “Play with your dog.” Upload your solution to your server, and paste the URL below.

Hint: Copy-and-paste the alert(...); line.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Including the jQuery library

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. This line downloads version 1.3.2. You can include a newer version, if you prefer.

One of the real pains of JS was that you would have to write different versions of your code for different browsers. What would work in Firefox, Chrome, and Safari would not work in Internet Explorer.

jQuery makes that problem go away. Write your code once, and jQuery will make it run everywhere. It also does animations and other cool things.

What now?

Let’s see how you write simple programs.

Understanding variables

Where are we?

You know how to put JavaScript on a page, and show some messages. To go any further, you’ll need to know about variables.

This lesson’s goals

By the end of this lesson, you should know:

  • A variable is a place in computer memory to store data.
  • Variables let you keep data for later.
  • Variables make your code easier to write, and understand.
  • Variables help you accumulate data, like totals and counts.
  • The difference between global variables and local variables.

First thing – the word “variable” in computing does not mean the same thing it does in math.

Some people think you need to know a lot of math to write programs. They’re wrong. Wrong, wrong, WRONG! Many professional programmers don’t even know how to spell “calculus,” let alone do it.

A variable is a container. It’s a piece of computer memory that you put data into.

Variables have names, like total or last_name, so the computer can tell them apart. Here are two variables in memory:

total last_name
21 Smith

Variables can contain numbers or text.

CC
CC

OK, a variable is a little box with information in it. Right?

Kieran
Kieran

Yes, that’s a good way to think of it.

CC
CC

So… why would I care?

Kieran
Kieran

Using variables makes writing JavaScript easier. But it’s better to show you. Let’s look at how you use variables.

Variables save data until you need it

Sometimes you use variables to hold data you have now, that you’ll need later.

Like cake tins. Suppose you have two pies and a cake.

Two pies and a cake

You eat the two pies, and a slice of cake – yum! But now you’re full.

What do you do with the rest of the cake? Throw it away?

CC
CC

Are you crazy? Throw away cake? No! No! No! (Shakes paw)

Renata
Renata

I’d keep the cake. I’m going to want it later. Ahhh… cake!

Kieran
Kieran

Where do you put the cake?

Renata
Renata

Somewhere I can find it later, when I’m hungry.

You put the rest of the cake in a cake tin.

Saving the cake

When you’re hungry again, you take the cake out of the container, and nom, nom, nom.

A variable is like the cake tin. It’s a place for storing data. You put data into the variable, and take it out later, when you’re ready to use it.

Let’s write some code that uses variables in this way. You go to the store and buy some chew toys. Specifically, the new brain chew toy:

Brain

How much do you pay for the brains? It depends on (1) how many brains you buy, and (2) how much each one costs. Multiply the two together, and that’s the total you pay.

total = number of brains x price per brain

So if you buy 5 brains, and they’re $4 each, you pay $20.

Click the button, and you’ll run a program that makes the calculation.

When you click the button, the browser asks you for the number of toys you want to buy. You type that in, and click OK. Let’s say you type 5:

How many toys

Figure 1. How many toys?

The browser can’t use that 5 right away. It needs another piece of information – the price – before it can use the 5 to compute the total. We want to keep the 5 for later.

How? We tell the browser to store the 5 in a variable. When we’re ready to compute the total, the browser can get the 5 – or whatever you typed – from the variable.

Here’s the code:

var number, price, total;
number = prompt('How many brain chew toys?');
price = prompt('Price each?');
total = number * price;
alert('Total: $' + total);

Figure 2. Some code

Line 1 creates three variables, that is, three containers in the computer’s memory. Line 2 makes an input box:

How many toys

Figure 1 (again). How many toys?

Whatever the user types gets put into the variable number, for later use.

Line 3…

price = prompt('Price each?');

...shows another input box. It stores what the user enters in the variable price.

Line 4…

total = number * price;

...gets the contents of number, and the contents of price. It multiplies them together (* means multiply), and puts the result into another variable, total.

Some geeks call * “splat.”

Line 5…

alert('Total: $' + total);

...gets the contents of total, and shows it in an output box.

Let’s see that again, but this time we’ll see the values of the variables as they change. They start off empty.

number price total
     

Try a few different calculations.

So, we know that a variable is a container for data. One use for a variable is to save data for later, until it is ready to use. In the example we just saw, the program took the number of brains the user entered, and stored it in the variable number, until the program was ready to use that data to work out the total cost.

Exercise: Dance the seconds away

Joe loves to play Dance, Dance, Revolution. He spends hours at it. How many seconds is that?

Write a program that asks the user for the number of hours and minutes, and displays the number of seconds. Here’s an example of what happens when the program runs:

Hours

Minutes

Seconds

The formula is:

seconds = hours * 3600 + minutes * 60

Use this template. Add your own JavaScript:

<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  <title>Seconds</title>
  <script type="text/javascript">
    $(document).ready(function() {
      $("#compute_seconds").click(function(){
        Your code here.
      });
    });
  </script>
  <body>
    <p>
      <button type="button" id="compute_seconds">Compute</button>
    </p>
  </body>
</html>

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Variables make programming easier

Here’s the code again:

var number, price, total;
number = prompt('How many brain chew toys?');
price = prompt('Price each?');
total = number * price;
alert('Total: $' + total);

Figure 2 (again). Some code

We could write the code without variables:

alert('Total: $' + prompt('How many brain chew toys?') * prompt('Price each?'));

Figure 3. Evil code

Kieran
Kieran

Which do you prefer? With or without variables?

CC
CC

The second one is less typing.

Kieran
Kieran

That’s true.

Renata
Renata

But it’s hard to understand. When I read it, by the time I’m half way through, I’ve forgotten what happened at the start.

Kieran
Kieran

Good point!

CC
CC

Renata’s right. It’s easier to deal with things in small chunks, rather than combining everything into one complex mess.

CC said something important there. It’s easier on your brain to break off a small piece of a problem, and solve that, then another small piece, then another. Try to keep everything in your brain at once, and your head will explode.

Variables let you do things in small steps. Do a step, put the results in a variable. Do another step, results into another variable. Until you’re done.

This code…

var number, price, total;
number = prompt('How many brain chew toys?');
price = prompt('Price each?');
total = number * price;
alert('Total: $' + total);

Figure 2 (again). Some code

... breaks the task into small pieces. This code…

alert('Total: $' + prompt('How many brain chew toys?') * prompt('Price each?'));

Figure 3 (again). Evil code

... mixes everything up. As a beginner, write your code in small chunks. Your brain will thank you.

Variables can accumulate data

Variables are used to accumulate totals and counts. This is a variant of keep-data-for-later.

Suppose you work at a carnival. You run the ferris wheel.

Ferris wheel

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

Ferris wheel pot

The number of tokens in the pot gets larger as the day goes on. A token for each new rider. The pot accumulates tokens.

A variable can be like that pot. The variables sits in memory, with a value in it:

ferris_count
12

A new rider comes along, and the value goes up:

ferris_count
13

Here’s a button you can click when a new person goes on the ride. Try it a few times.



Here’s the code:

<script type="text/javascript" >
$(document).ready(function(){
  var ferris_count = 0;
  $("#ferris_button").click(function(){
    ferris_count = ferris_count + 1;
    alert("Ferris wheel count: " + ferris_count);
  });
});
</script>
<p>
  <button type="button" id="ferris_button">Count</button>
</p>

Figure 4. The ferris pot

Line 3 creates a variable called ferris_count in the computer’s memory, and puts zero in it. This “initializes” the variable, giving it a starting value.

The line is outside the click function. This is important! Line 3 only runs once, when the page has been loaded. We only want to set ferris_count to zero once. More on that later.

When the button is clicked, lines 5 and 6 run. Here’s line 5:

ferris_count = ferris_count + 1;

This says “Get the value from ferris_count, add 1 to it, and put the result into ferris_count.” So, if ferris_count has 0 in it before line 5 is run, it would have 1 in it after line 5 has run. If it had 18 before, it will have 19 after. This is what we want: click the button, the variable goes up by one.

As it turns out, “add 1 to a variable” is common in programming. So there’s a shortcut in JavaScript:

ferris_count ++;

This does the same thing as ferris_count = ferris_count + 1;.

Line 6 shows the current value of the variable:

alert("Ferris wheel count: " + ferris_count);

You can watch the program as it runs. Click the Count button to get started. You can run the statements in the click() event one at a time, and watch what happens.

Scope

Here’s the ferris wheel code again:

<script type="text/javascript" >
$(document).ready(function(){
  var ferris_count = 0;
  $("#ferris_button").click(function(){
    ferris_count = ferris_count + 1;
    alert("Ferris wheel count: " + ferris_count);
  });
});
</script>
<p>
  <button type="button" id="ferris_button">Count</button>
</p>

Figure 4 (again). The ferris pot

Line 3 declares (creates) the variable:

var ferris_count = 0;

Something important: the variable is created outside the click function.

var ferris_count = 0;Variable created.
$("#ferris_button").click(function(){
    ferris_count = ferris_count + 1;Variable used.
    ..
});

Why? It has to do with something called “variable scope.” It’s a complex topic, but we don’t care about all the details. I’ll give you just two simple rules. Here’s the first one:

Use global variables when you want to count or total something. Declare the variables outside any function.

That’s what the ferris wheel example does. We want the browser to remember how many button clicks there were, so the next click adds one to that value. So:

var ferris_count = 0;Variable created.
$("#ferris_button").click(function(){
ferris_count = ferris_count + 1;Variable used.
..
});

ferris_count is declared outside the click() function. The memory for ferris_count is allocated when the page loads. It stays there, even when the user is not clicking on anything.

Suppose we mess it up:

<script type="text/javascript" >
$(document).ready(function(){
  $("#ferris_button").click(function(){
    var ferris_count;
    ferris_count = ferris_count + 1;
    alert("Ferris wheel count: " + ferris_count);
  });
});
</script>
<p>
  <button type="button" id="ferris_button">Count</button>
</p>

Figure 5. The ferris pot – brokeh

ferris_count is declared inside the click() function this time. (I left off the = 0 part (it used to be var ferris_count = 0), since that will just set it to zero each time.)

When the user clicks, line 4 will create the variable. Line 5 will add to it. Line 6 shows it. Line 7 ends the function, and destroys the variable!

That’s right. Variables declared inside a function are removed from memory when the function ends.

Click this button to run Figure 5:



What the…? The result varies between browsers. This is what I got in Firefox:

Brokeh output

Figure 6. Brokeh output

NaN means “not a number.” Let’s not worry about why the browser does that. The point is, it doesn’t work.

Variables declared outside any function are called “global variables.” They are created when the page loads, and vanish when another page loads.

Variables declared inside a function (like a click() function) are called “local variables.” They are created when the function starts, and vanish when the function ends. Each time the click() function runs, local variables are created and destroyed.

Remember the first scope rule:

Use global variables when you want to count or total something. Declare the variables outside any function.

Now let’s talk about the second scope rule.

Using the same variable in different functions

Suppose you quit the ferris wheel job. You get a new job at a local movie theater, counting ticket sales. Adults and children are counted separately.

Here are three buttons. One to count adult tickets, one to count child tickets, and the third to show how many of each type have been sold. Oh, and a fourth button to reset everything back to zero.

Play around with the buttons for a while.

 

Now let’s peek inside the code, and check out the variables in memory.

The page

 

Memory
adult child
0 0

Here’s the code:

<script type="text/javascript">
  $(document).ready(function() {
    var adult = 0;
    var child = 0;
    $("#sold_adult").click(function(){
      adult ++;
    });
    $("#sold_child").click(function(){
      child ++;
    });
    $("#show_sales").click(function(){
      alert("Adults: " + adult + "   Children: " + child);
    });
    $("#reset_tickets").click(function(){
      adult = 0;
      child = 0;
    });
  });
</script>
...
<button id="sold_adult" type="button">Sold adult ticket</button>
<button id="sold_child" type="button">Sold child ticket</button>
<button id="show_sales" type="button">Show sales</button>
...
<button id="reset_tickets" type="button">Reset</button>

Figure 7. The code

Lines 3 and 4 declare the two variables, adult and child. They are global variables, since both are declared outside any function. The variables are created in memory when the page loads, and removed when the page is unloaded.

Global variables are available to every function. For example, three separate click() functions use the variable adults.

Different functions can do different things to the same variable. The $("#sold_adult").click() function adds to adults. The $("#show_sales").click() function displays the value in adults. $("#reset_tickets").click() sets the variable back to zero.

This shows the second rule for variable scope:

Use global variables when you want to share data between functions.

Exercise: Count the goodies

Create a page that counts the donuts and muffins sold by a bakery. The page should look like this:

Page

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

Sales

You can start with this code:

<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <title>Bakery sales</title>
    <script type="text/javascript">
      $(document).ready(function() {
      
        $("#sold_donut").click(function(){
          
        });
        $("#sold_muffin").click(function(){
          
        });
        $("#show_sales").click(function(){
          
        });
      });
    </script>
  </head>
  <body>
    <p>
      <button id="sold_donut" type="button">Sold a donut</button>
    </p>
    <p>
      <button id="sold_muffin" type="button">Sold a muffin</button>
    </p>
    <p>
      <button id="show_sales" type="button">Show sales</button>
    </p>
  </body>
</html>

Upload your solution to your server, and enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

  • A variable is a place in computer memory to store data.
  • Variables let you keep data for later.
  • Variables make your code easier to write, and understand.
  • Variables help you accumulate data, like totals and counts.
  • Use global variables when you want to count or total something.
  • Use global variables when you want to share data between functions.

What now?

On this page, you saw code that runs when the user does something, like clicks on a button. Let’s talk about that button clicking.

Events

This page’s goals

In this lesson, you’ll learn:

  • What an event is.
  • How to tie code to events.
  • How to show and hide page elements.

Events: things that happen

Suppose we want users to fill in a form on a Web site. We give instructions for filling out the form. But we don’t want the instructions to get in the way. The instructions will start out hidden, but users can show them if they want.

Try this page. Click on “Show instructions” and see what happens. (The “v” represents an image of a down arrow.)

An event is something that happens on a Web page, like a user clicking on text. Your code tells the browser what to do when the event happens.

Your browser knows about lots of events. Try this exercise.

Exercise Name the events

Here are some elements: a button, some text, and an input field:

Some text

As you interact with them, they’ll generate events. The name of the event will appear to the right of each element. For example, if you rest the mouse cursor on the button:

Page

Write down the names of the events that each element generates (e. g., “Button: mouse over”). Enter the events below, under Your solution.

Hint: There are four events each for the button and text, and five events for the field.

Note: This only shows you the most common events the elements can generate. There are a few more.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Let’s get back to the show-and-hide-help task. Here are two pieces of code. They’re not in JavaScript, just English.

Two pieces of code

Figure 1. Two pieces of code

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

Two functions

Figure 2. Two functions

You’ll learn more about functions later.

Each function in Figure 2 is just a single line. That’s OK. Functions can be any length.

We want the browser to run the first function when the user clicks on “Show help v.” We want the browser to run the second function when the user clicks on “Hide help ^.” Here’s how we would put them together.

Two pieces of code again

Figure 3. Two functions again

Here’s the general template for event handlers, that is, functions that run when an event is triggered:

Event template

Figure 4. Event template

“object” is the thing that the event happens to. “event” is the event’s name, like “click” or “mouse over.”

You can make functions do lots of stuff. Create things, erase things, hide things, show things, change the text of paragraphs, headings and other things, show popup messages to the user, ... lots of stuff.

Here’s an unfriendly program.

Evil program

Figure 5. Evil program

When the user clicks on the help prompt, the browser runs the function. It would play a sound, erase the page, and popup a message.

You can have all sorts of fun with users.

They might not think it’s fun. Some people have no sense of humor.

Here’s another version:

Annoying program

Figure 6. Annoying program

Instead of erasing the page, it just hides it, and brings it back later.

Programmers get up to tricks like this. “Easter eggs” are things that are buried in programs, surprises for users. They’re usually harmless. For example, type this into the address bar of Firefox:

about:mozilla

What you see is a strange dig at Internet Explorer.

Try this:

about:robots

One more. This isn’t really an easter egg, it’s just the way the tech works.

chrome://browser/content/browser.xul

Firefox inside Firefox!

Enough distraction. Here’s the template again:

Event template

Figure 4 (again). Event template

This is actually not too far from real code. jQuery has a click() event, that fires when the user clicks on something. We can use that to trigger the state changes.

There’s one other jQuery event we’ll need. The browser doesn’t watch for all possible events. Instead, we tell it what events to watch for. Here are the event handlers again:

Two functions again

Figure 3 (again). Two functions again

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

Page load event

Figure 7. Page load event

jQuery has an event called ready(). The ready() event happens just after a Web page has finished loading, but before the user is allowed to interact with it. Usually you put initialization code in the ready() event. That’s code that runs once, to finish getting the page ready for the user.

Write the HTML your program will work with

Back to the show-hide-help example. This page.

Let’s write the HTML for the page. Most JavaScript code messes with HTML objects, like paragraphs.

<p>Please fill in this form:</p>
<p>Show instructions v</p>
<p>Hide instructions ^</p>
<blockquote>
  Helpy help help.
</blockquote>
<p>FORM</p>

Figure 8. HTML

You can see the HTML objects the program will mess with: the help prompts that people will click on (lines 2 and 3), and the help message that will be shown and hidden (lines 4 to 6). You can see the page as it is so far.

Renata
Renata

How come I can see both help prompts?

Kieran
Kieran

We’ll change it in a moment, so that the user will see only one or the other.

Name things

So far, we’ve worked out what the program will do, and identified events that we will tie code to. The next step is to name things.

When you want to change something on a page, you need to be able to refer to it. The easiest way to do that is with the id attribute.

Here’s an example:

<blockquote id="instructions">Helpy help help.</blockquote>

Figure 9. The id attribute

An attribute is something you attach to an HTML tag, that modifies it in some way. There are many different attributes. For now, the only one we care about is id.

Make sure that every id is unique within a page. That is, there should only be one element with id of instructions on any page.

There’s another attribute called name. Don’t use it yet. It means something different.

Once we’ve given an element an id, we can mess with it. In our example, we need to give ids to:

  • The help prompts “Show instructions” and “Hide instructions.” We’ll attach code to their click() events
  • The instructions, which will be visible or not.

So we’ll give ids to these three things. Here’s the code:

<p>Please fill in this form:</p>
<p id="instructions_title_show">Show instructions v</p>
<p id="instructions_title_hide">Hide instructions ^</p>
<blockquote id="instructions">
  Helpy help help.
</blockquote>
<p>FORM</p>

Figure 11. Giving HTML elements ids

CC
CC

There are four <p> tags, but only two have ids. Why?

Kieran
Kieran

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.

Renata
Renata

So if you don’t need to, don’t attach an id?

Kieran
Kieran

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.

Attach code to events

OK, we’re ready to attach code to events.

Here’s the entire page so far.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <title>Instructions</title>
  </head>
  <body>
    <p>Please fill in this form:</p>
    

Show instructions v

Hide instructions ^

<blockquote id="instructions"> Helpy help help. </blockquote> <p>FORM</p> </body> </html>

Figure 12. The page so far

Note that we’ve loaded jQuery in line 5.

I usually don’t write programs all at once. Instead, I write just a piece, and then try it out. This is a good practice, since it limits the number of things that can go wrong.

Let’s try that. We’ll start by hiding the instructions when the page loads.

<script type="text/javascript">
  $(document).ready(function() {
    $("#instructions").hide();
  });
</script>

Figure 13. Hiding instructions

Remember, everything between $(document).ready(function() { and }); runs once the page has been loaded.

The $("#instructions") in line 3 tells jQuery to find some elements on the page. Which ones? The ones that have an id of instructions. Be sure to include the #. This is what tells jQuery to look at the id attribute, and not some other attribute. Leaving out the # is a common error.

There should be only one element with an id of instructions. If there is more than one, browsers can start acting strangely.

The rest of the statement tells jQuery what to do with the elements it finds. .hide() tells jQuery to hide them.

In English, $("#instructions").hide(); is:

Find all the elements with an id of instructions, 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.

Testing event triggering

We could write the rest of program in one step, but we won’t. Let’s just get the event binding to work. Remember that “binding” ties code to an event.

Let’s write it so that clicking on the instruction title shows a simple message. Here’s the new code.

<script type="text/javascript">
  $(document).ready(function() {
    $("#instructions").hide();
    $("#instructions_title_show").click(function() {
      alert("Clicky clicky 1.");
    });
    $("#instructions_title_hide").click(function() {
      alert("Clicky clicky 2.");
    });
  });
</script>

Figure 14. Eventing

You can try it.

$("#instructions_title_show") means “find everything with an id of instructions_title_show” (don’t forget the #). There is only one thing with that id. .click(function() { means “Here’s what to do with the user clicks on it.”

What happens when the user clicks? S/he gets a message. Try it if you haven’t already.

Toggling visibility

For the next step, We’ll do this:

<script type="text/javascript">
  $(document).ready(function() {
    $("#instructions").hide();
    $("#instructions_title_show").click(function() {
      $("#instructions").show('fast');
    });
    $("#instructions_title_hide").click(function() {
      $("#instructions").hide('fast');
    });
  });
</script>

Figure 15. Toggling visibility

You should try it.

Again, $("#instructions") means “Find everything with an id of instructions. .show('fast') means “Show it quickly.” The speed can be 'medium' or 'slow' as well, or we can leave it out, which would be .show().

You can also do something like .show(5000). This will run the effect over 5,000 milliseconds (ms). An ms is 1,000th of a second, so the effect would take 5 seconds to complete. ms is a common unit in computing.

Hmm, can you guess what hide('fast') does?

Exercise: Secret of a happy life 1

Start with this code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <title>Secret of Life</title>
    <script type="text/javascript">
      $(document).ready(function() {

      });
    </script>
  </head>
  <body>
    <p id="secret_instructions">Click me to learn the secret of a happy life.</p>
    <h1 id="secret">Dogs!</h1>
  </body>
</html>

Add code to hide secret when the page first loads, and then show it when the user clicks on secret_instructions.

Upload your solution to your server, and enter its URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Changing the help prompt

We’re almost done.

Right now, we have both help prompts showing:

Both prompts

Figure 16. Both prompts

We want to hide one of them when the page loads. When the user clicks, we want to change which of the help prompts is visible.

This will do it:

<script type="text/javascript">
  $(document).ready(function() {
    //The page has loaded.
    //Hide the instructions.
    $("#instructions").hide();
    //Hide one of the help prompts.
    $("#instructions_title_hide").hide();
    $("#instructions_title_show").click(function() {
      //User has clicked on the "Show" prompt.
      //Switch the help prompt.
      $("#instructions_title_show").hide();
      $("#instructions_title_hide").show();
      //Show the instructions.
      $("#instructions").show('fast');
    });
    $("#instructions_title_hide").click(function() {
      //User has clicked on the "Hide" prompt.
      //Switch the help prompt.
      $("#instructions_title_hide").hide();
      $("#instructions_title_show").show();
      //Hide the instructions.
      $("#instructions").hide('fast');
    });
  });
</script>
...
<body>
  <p>Please fill in this form:</p>
  <p id="instructions_title_show">Show instructions v</p>
  <p id="instructions_title_hide">Hide instructions ^</p>
  <p id="instructions">These are the instructions.</p>
  <p>FORM</p>
</body>

Figure 17. Prompt visibility

You can try this page.

Line 7 hides the “Hide help ^” prompt. It is inside the ready() event. It runs when the page loads. So when the user first sees the page, only the “Show help v” prompt will be visible.

Lines 11 and 12 run when the user clicks on the “Show” prompt. They change which help prompt is visible.

Two other things to notice. First, there are lots of comments. They all begin with //. They explain how the program works.

Second, the code is indented. Each time there is a new tag or brace ({) opened, I added two spaces. Some people use four spaces; do whatever you like.

The browser does not care about indenting. It will not affect the way the code runs. But it makes the code much easier for people to read.

Especially humans. They’re easily confused.

A single click target

Here’s Figure 16 again:

Both prompts

Figure 16 (again). Both prompts

Another option is to have just one click target, like this:

One click target

Figure 18. One click target

This isn’t as good for the user, since the prompt (show/hide) is less specific than two separate prompts. But the code is easier to write:

<script type="text/javascript">
  $(document).ready(function() {
    //The page has loaded.
    //Hide the instructions.
    $("#instructions").hide();
    $("#instructions_show_hide").click(function() {
      //User has clicked on the "Show/hide" prompt.
      //Toggle the instructions.
      $("#instructions").toggle('fast');
    });
  });
</script>
...
<body>
  <p>Please fill in this form:</p>
  <p id="instructions_show_hide">Show/hide instructions</p>
  <p id="instructions">These are the instructions.</p>
  <p>FORM</p>
</body>

Figure 19. Toggle function

Look at line 9:

$("#instructions").toggle('fast');

Instead of show or hide, there’s toggle. If something is showing, toggle will hide it. If something is hiding, toggle will show it. It switches back and forth.

You can try the page.

A better mouse cursor

Try this version of the page. Notice that the mouse cursor changes to a hand when the user moves it over one of the help prompts. This gives the user a hint that the element is clickable.

I added the following CSS to the page:

#instructions_title_show:hover,
#instructions_title_hide:hover {
  cursor: pointer;
}

Figure 20. Styling the cursor

There are several new things here. First, there’s the # in front of the selectors. This is the same syntax that jQuery uses. #instructions_title_show means “find the thing with the id of instructions_title_show, and apply the style.” In fact, jQuery borrowed this syntax from CSS.

The second new thing is the :hover. This is called a pseudo-class. :hover means “apply the styles when the mouse is on the element.” You can apply any styles at all. You can change the font, color, background color, whatever. For example, you could do this:

<style type="text/css">
  #instructions_title_show:hover {
    cursor: pointer;
    font-weight: bold;
    font-size: 24px;
    color: red;
    background-color: yellow;
  }
</style>

Figure 21. Going too far

You could do this, but I wouldn’t recommend it. The point is, you can change anything.

Another new thing in Figure 20 is the cursor style. This changes the mouse cursor. There are lots of cursors you can use. See the SitePoint reference page for a list.

Finally, you can apply the same styles to more than one type of thing at the same time. This:

selector1, selector2 {
   style rules;
}

applies the rules to all the items selected by selector 1, and all of the items selected by selector 2. For example, let’s say I wanted to make all <h1>s, <h3>s, and <h5>s dark red, and all <h2>s, <h4>s, and <h6>s dark green. Here’s what I would do:

<style type="text/css">
  h1, h3, h5 {
    color: #660000;
  }
  h2, h4, h6 {
    color: #006600;
  }
</style>

Figure 22. Heading styles

Make sure you use a comma (,) to separate the items. If you leave it out, the rule won’t work.

Renata
Renata

Wow, that took a long time. For such a simple program.

Kieran
Kieran

Only because this was our first program. Every program we write will use events and such in the same way. So we won’t have to go as slowly.

Exercise: Tell a dog joke

Write a program to show the first part of a dog joke:

First part of a dog riddle

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

Riddle answer

Upload you solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

On this page, you learned how to:

  • Plan a simple program by drawing its states.
  • Tie code to events.
  • Show and hide elements on a page.

All cool stuff!

What now?

Let’s see how you can change the actual text of an element, and the CSS that’s applied to it.

Changing text

Where are we?

In the previous lesson, you learned how to add interactive help to a Web page. Let’s see how you can make more changes to a page.

This lesson’s goals

By the end of this lesson, you should:

  • Know how to change the text of an element, e.g., change the text inside a <p>.
  • Know how to get the text of an element.
  • Know how to add a CSS class to an element.
  • Know how to remove a CSS class from an element.

A simple quiz

Try this page.

How do we create this page? First, we need to attach a .click() event to each of the answers.

Quiz events

Figure 1. Quiz events

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

Right/wrong messages

Figure 2. Right/wrong messages

We could write separate event handlers for all four answers (remember that an event handler is code attached to an event). But there’s an easier way.

Let’s start with this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <title>Instructions</title>
    <style type="text/css">
      body {
        background-color: #FFFFEE;
        font-family: Verdana, sans-serif;
        font-size: 14px;
      }
      .right, .wrong {
        cursor: pointer;
      }
      #result {
        font-weight: bold;
      }
    </style>
    <script type="text/javascript">
      $(document).ready(function() {
        Program goes here.
      });
    </script>
  </head>
  <body>
    <h1>Quiz</h1>
    <p>What is 4 x 7?</p>
    <p>Please click on the right answer.</p>
    <p class="wrong">a. 14</p>
    <p class="wrong">b. 47</p>
    <p class="right">c. 28</p>
    <p class="wrong">d. I will never need to know.</p>
    <p id="result"></p>
  </body>
</html>

Figure 3. Getting started

The result paragraph (line 34) is where the result will go, with the “Right” or “Wrong” message. That’s why the <p> has an id: our code needs to refer to it.

Our code needs to refer to the answers as well, so it can attach event handlers. Look at lines 30 to 33, and you’ll see something different. I used class instead of id. Why?

Remember that ids have to be unique. There can only be one element on a page with an id of dog. Not so with class. There can be an unlimited number of elements with the same class name. I can write one event handler for anything with a class of wrong, and it will apply to all elements with that class.

Let’s look at the CSS. The rule in lines 8 to 12 sets up some defaults for the page. Since all of the page’s content is inside the <body>, the rule applies to all elements.

The rule in lines 13 to 15 has two selectors: .right and .wrong. The selector .right says, “Apply this rule to all elements that have a class of right.” Remember to use # for id, and . for class. The selector .wrong says, “Apply this rule to all elements that have a class of wrong.” There’s a comma (,) between the selectors, so the rule applies to both classes.

The rule itself (line 14) sets the mouse cursor to a pointing hand.

Finally, the rule in lines 16 to 18 applies to the element with the id of result. A # means “look at id.” A . means “look at class.”

Renata
Renata

Let’s see if I have this right. You have an event handler, that’s going to do something. If you want to attach that handler to just one thing on the page, use id. Is that right?

Kieran
Kieran

Yes.

Renata
Renata

But if you want to attach the same handler to more than one thing, use class.

Kieran
Kieran

Right!

CC
CC

And you do the same with CSS rules, that change the look of things. If a particular look is going to be used on just one thing, like just one <p>, use an id. That means <p id="whatever"> in the HTML, and #whatever in the CSS.

Kieran
Kieran

Indeed.

CC
CC

But if you want to give more than one thing the same look, use <p class="whatever"> in the HTML and .whatever in the CSS.

Kieran
Kieran

Yes, you’ve got it! W00fs for both of you!

OK, let’s look at the code. We’ll need events for both the classes.

<script type="text/javascript">
  $(document).ready(function() {
    $(".right").click(function() {
      Something
    });
    $(".wrong").click(function() {
      Something else
    });
  });
</script>

Figure 4. Events

The first one will apply to the one element that has a class of right. The second one will apply to the three elements that have a class of wrong.

Renata
Renata

Could you have used an id for right, since there is only one?

Kieran
Kieran

Yes, I could. But a future question might have more than one right answer. A question like, “Which of these people signed the American Declaration of Independence?” might list several names, more than one of which might be correct. I used class just in case.

In the hiding help example on the previous page, we put in two different help prompts. We could have included two different versions of the result paragraph, one with the “Right” message, and the other with the “Wrong” message.

I didn’t do that here, because I want to show a different way of doing things. We just have one place to show the result:

<p id="result"></p>

What we’ll do is change the content of that, depending on whether the answer is right or wrong.

Here’s the code:

<script type="text/javascript">
  $(document).ready(function() {
    $(".right").click(function() {
      $("#result").text("Right! W00f!");
    });
    $(".wrong").click(function() {
      $("#result").text("Sorry, that's wrong.");
    });
  });
</script>

Figure 5. The final code

text() will set the content of an element. This:

$("#result").text("Right! W00f!");

means “Find all elements with an id of result, and set their text to ‘Right! W00f!’.” Only one element has an id of result. As always, don’t forget to add the # when dealing with ids, and . for classes.

Any text can go inside text(). It can be a fixed message, like this example. But it doesn’t have to be.

Making a train

Try this page. Click on the “Add” messages to add different types of cars to the train.

This is different from the last one, in that the output is always growing. When you click on an “Add,” the output doesn’t get replaced with a new value. Instead, some new text is added to what is already there.

Here is the page without the JavaScript:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <title>Make a train</title>
    <style type="text/css">
      body {
        background-color: #FFFFEE;
        font-family: Verdana, sans-serif;
        font-size: 14px;
      }
      #add_passenger_car,
      #add_freight_car {
        cursor: pointer;
      }
      #train {
        font-weight: bold;
      }
    </style>
    <script type="text/javascript">
    </script>
  </head>
  <body>
    <h1>Make a train</h1>
    <p id="add_passenger_car">Add passenger car</p>
    <p id="add_freight_car">Add freight car</p>
    <h2>Your train</h2>
    <p id="train">Engine</p>
  </body>
</html>

Figure 6. Start of the train

Lines 26 and 27 are the things you can click on. They need ids, because we need to bind code to their click() events.

Line 29 is the output. It needs an id as well, so we can change it.

Here is the JavaScript:

<script type="text/javascript">
  $(document).ready(function() {
    $("#add_passenger_car").click(function() {
      $("#train").text( $("#train").text() + ' passenger' );
    });
    $("#add_freight_car").click(function() {
      $("#train").text( $("#train").text() + ' freight' );
    });
  });
</script>

Figure 7. Train code

Look at line 4, which adds a passenger car to the train. Read it from the inside out:

Start here

That’s what the browser does when it runs JavaScript. It does the stuff inside parentheses (the () ) first. So the first thing the browser runs is:

$("#train").text()

There’s nothing inside the (). When it sees that, jQuery gets the current text. So, what .text() does depends on whether there is something inside the ():

$("#train").text("W00f") sets the text to W00f.

$("#train").text() gets the text, whatever it is.

Now let’s look at some more of line 4

Next

This gets the text from train, and appends “ passenger” to the end of it. So if train had “Engine” in it, we would end up with “Engine passenger”. If train had “A zombie will eat every” in it, we would end up with “A zombie will eat every passenger”.

This line also shows that you can mix single quotes (') and double quotes ("). Just match pairs. So if you start with a ", close it with a ".

Now let’s look at all of line 4:

$("#train").text( $("#train").text() + ' passenger' );

This says: Get the text of the element with an id of train, add “ passenger” onto the end of it, and put the result into the element with an id of train.

Exercise: Clearing the train

Change the train example. Add “Clear” below the two “Add” controls. Clicking on “Clear” sets the train back to just “Engine”.

Hint: Ask yourself, “What changes on the page when the user clicks Clear?”

Upload your solution to your server, and put its URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Cities in Cyrodiil

Oblivion is one of my favorite computer games. It’s a mixture of a role-playing game and a first-person shooter. I’ve waste…, er, invested way too much time on it.

The game is set in the nation of Cyrodiil. Cyrodiil has a bunch of cities with strange names. Let’s make a Cyrodiil cities quiz. But this one will be a little different from the last one we did.

Try the page. Click on the city names, to learn whether each one is real or fake.

Here’s the HTML and CSS:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <title>Oblivion cities</title>
    <style type="text/css">
      body {
        background-color: #FFFFEE;
        font-family: Verdana, sans-serif;
        font-size: 14px;
      }
      .real, .fake {
        cursor: pointer;
      }
      .highlight {
        font-size: 16px;
        font-weight: bold;
        color: #660000;
      }
    </style>
    <script type="text/javascript">
       JavaScript goes here.
    </script>
  </head>
  <body>
    <h1>Oblivion cities</h1>
    <p>
      Which of the following are cities in Cyrodiil?
      Guess whether each one is real (in the game) or 
      fake. Click on it to see the answer.</p>
    <ul>
      <li class="fake">Arcasha</li>
      <li class="real">Kvatch</li>
      <li class="real">Cheydinhal</li>
      <li class="fake">Xenithar</li>
      <li class="fake">Vercingetorix</li>
      <li class="real">Skingrad</li>
    </ul>
    <p id="real_city">Real</p>
    <p id="fake_city">Fake</p>
  </body>
</html>

Figure 8. Cities quiz

The cities are in a list, from lines 33 to 40. Each city has a class of either real or fake. When the user clicks on a city, we want to highlight “Real” (line 41) if it’s a real city in the game, or “Fake” (line 42) if it’s not.

Let’s write the JavaScript. I start with the ready() event.

$(document).ready(function() {

});

Figure 9. ready() event

This is run when the page has loaded.

I’ll bind code to the click() events of the real and fake items:

$(document).ready(function() {
  $(".fake").click(function() {

  });
  $(".real").click(function() {

  });
});

Figure 10. Binding code to events

Clicking on an element with the class fake will run the code at line 3. Clicking on an element with the class real will run the code at line 6.

If the city is real, we want to highlight “Real,” and make sure that “Fake” is not highlighted. How to highlight something? A clue is in the CSS:

body {
  background-color: #FFFFEE;
  font-family: Verdana, sans-serif;
  font-size: 14px;
}
...
.highlight {
  font-size: 16px;
  font-weight: bold;
  color: #660000;
}

Figure 11. CSS to highlight something

The font size is normally 14 pixels (line 4). Its normal color is black; that’s the browser’s default, and nothing in the CSS changes that for regular text.

But if we apply the class highlight to something, its text will get larger, bold, and dark red. So we can highlight something by giving it the class highlight. Removing the class will set it back to regular text.

jQuery gives us addClass() and removeClass(). They, er, add and remove classes. Here’s the final code:

$(document).ready(function() {
  $(".fake").click(function() {
    $("#fake_city").addClass("highlight");
    $("#real_city").removeClass("highlight");
  });
  $(".real").click(function() {
    $("#real_city").addClass("highlight");
    $("#fake_city").removeClass("highlight");
  });
});

Figure 12. Code for changing classes

When a user clicks on an element with the class fake (line 2), the element fake_city is given the highlight class (line 3), and the highlight class is removed from real_city (line 4). If the class wasn’t there, no harm is done.

Exercise: Which technology?

Create a page like the one on cities in Cyrodiil. It will list words that are from HTML, CSS, or JavaScript/jQuery. Click on each word, and the page will highlight the tech that name is from.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Using id for JavaScript, and class for CSS

Here’s another way to do the cursor style in Figure 6:

Remove this:

#add_passenger_car,
#add_freight_car {
  cursor: pointer;
}
...
<p id="add_passenger_car">Add passenger car</p>
<p id="add_freight_car">Add freight car</p>

Replace with:

.car {
  cursor: pointer;
}
...
<p id="add_passenger_car" class="car">Add passenger car</p>
<p id="add_freight_car" class="car">Add freight car</p>

Figure 13. id and class

Here, the <p>s have both an id and a class. The id is used in the JavaScript, and the class is used in the CSS.

It can be convenient to do this sometimes. Suppose I wanted to change several attributes of the text “Add passenger car” at once. Maybe make it bold, green, and in a different typeface. Whatever. I could define another class called supercar.

.supercar {
...
}

In JavaScript:

$("#add_passenger_car").removeClass("car");
$("#add_passenger_car").addClass("supercar");

This can be shortened to:

$("#add_passenger_car").removeClass("car").addClass("supercar");

When I do this, I usually format it like this:

$("#add_passenger_car")
   .removeClass("car")
   .addClass("supercar");

Makes it easier to read.

So, if you want to change the look of an element in a JavaScript program, it’s often easier to define both a class and an id. The look is defined entirely by the class, and never by the id. You can easily mess with the class, using addClass and removeClass.

Summary

In this lesson, you learned some more JavaScript/jQuery:

  • text("stuff") will set the text of an element.
  • text() will get the text of an element.
  • addClass() adds a CSS class to an element.
  • removeClass() removes a CSS class from an element.

What now?

Let’s see how we can get more data from the user, other than just clicks.

Getting data from the user

Where are we?

You know how to show and hide elements, change their text, and add and remove classes. You know how to tie these things to click events.

Now lets ask users questions, and do things with their answers. Even more w00f!

Let’s do it!

There are lots of ways to get data from users. The most familiar way is to use Web forms, so let’s start there.

Form processing is quite complicated, so we’re not going to look at it all here. In fact, we’re going to take just a couple of pieces, and use them in ways that some Webers will object to.

Calm down, Webers! We’ll get to correct form processing later. But for now, let’s keep it simple, so we can start exploring.

Forms are created with HTML tags. We’ll use two of them here: the <input> tag and the <button> tag.

Getting text data

The <input> tag is used for a lot of different things in HTML. We’ll just use one version of it, the one that creates text input fields.

Here’s an example:

<input type="text" id="my_field">

Here’s what this looks like in your browser:

The type attribute tells the browser what type of field you want. There are check boxes, radio buttons, and others. Let’s stick to text for now.

Buttons

The other tag is <button>. Here’s an example:

<button type="button" id="go">Click me!</button>

Here’s what it looks like in your browser:

Buttons looks different on other sites. I’ve used CSS to make CoreDog’s buttons match the rest of the CoreDogs look. Part of the branding of this site.

There are two types of buttons, regular buttons and submit buttons. We’re using the regular buttons here. That’s what type="button" tells the browser.

The text inside the tag – Click me! or whatever – supplies the button’s caption, that is, the text on the button.

Hello world!

Time for the obligatory “hello world” example. We’ll do it in stages.

Let’s do the first step, just make the HTML and a button that does something. Please have a look at this page.

Here is the code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <title>Hello world!</title>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#user_name_output").hide();
        $("#go").click(function() {
          alert('You clicked me!');
        });
      });
    </script>
  </head>
  <body>
    <p>
      Please type your name below and click the button.
<input type="text" id="user_name_input"> <button type="button" id="go">Go!</button> </p> <h1 id="user_name_output"></h1> </body> </html>

Figure 1. Starting “Hello world!”

Line 19 creates a text input field. Line 20 creates a button right next to it. Line 22 gives a place for output.

The code in lines 9 to 12 is run when the page is ready. Line 9 hides the output area. Line 10 sets up an event handler, run when the user clicks the button.

So far, so good. Let’s add the rest of the code. When the user clicks the button, what we want to happen is this:

  • Get whatever the user typed.
  • Put it in the output area.
  • Show the output area.

Here’s some code:

$("#go").click(function() {
  //Get the user's name.
  user_name = $("#user_name_input").val();
  //Add it to the output.
  $("#user_name_output").text("Hello " + user_name + "!");
  //Show the output.
  $("#user_name_output").show('slow');
});

Figure 2. Code

Please try it.

Lines 2, 4, and 6 are comments. Any line in your JavaScript that starts with // is ignored by your browser. The comments help explain what the code is doing.

Adding comments is good practice. When someone needs to change what the code on the page does, s/he will first read the comments to figure out how the current code works. Good comments make that task easier.

Line 3 gets whatever the user typed. $("#user_name_input").val() finds the field with the id of user_name_input, and gets its contents. val() is an attribute of form fields. It returns the contents of the field.

What does line 3 do with the value? It puts it in a variable.

user_name = $("#user_name_input").val();

A variable is a temporary holding place in the computer’s memory. When the browser sees user_name for the first time, it grabs some memory and labels it user_name.

The = in line 3 says “Take the value on the right, and put it into the variable on the left.” So line 3 takes the value in the text field, and stores it in the variable user_name.

Look at line 5:

$("#user_name_output").text("Hello " + user_name + "!");

"Hello " + user_name + "!" says to take the text “Hello “, put the contents of the variable user_name on the end, and then put the text “!” on the end of that.

Huh!?

Let’s take a side trip, to see how this works.

Variables and constants

user_name = "Tim";
alert("user_name");
alert(user_name);
alert("user_name: " + user_name);
alert(user_name + "Taylor");

Figure 3. Variables and constants

Line 1 shows the difference between variables and constants. user_name is a variable. As just explained, a variable is a temporary storage place in the computer’s memory for some data. You can put data into it, like Tim, or Lenny, or Katherine.

"Tim" is a constant. It will always be, well, "Tim". The quotes ("") are JavaScript’s way of representing fixed text.

Line 2 is:

alert("user_name");

It outputs a constant. "user_name" is a fixed value that will never change. This does not refer to the variable user_name. "user_name" means the exact text "user_name", just as "Renata likes treats" refers to the exact text "Renata likes treats".

On the other hand, line 3 outputs the contents of the variable user_name.

alert(user_name);

The line doesn’t have quotes around user_name. The browser says to itself, “Self, user_name must be a variable. I’ll get its value from memory, and show whatever that value is.”

Here’s a picture of these two lines in action.

A variable and a constant

Figure 4. A variable and a constant

The first line outputs whatever is between the quotes exactly as is. The second line fetches the contents of the variable user_name from memory, and outputs that.

Here’s Figure 3 again.

user_name = "Tim";
alert("user_name");
alert(user_name);
alert("user_name: " + user_name);
alert(user_name + " Taylor");

Figure 3 (again). Variables and constants

Let’s look at line 4. It takes the exact text user_name: (with a colon and a space at the end), appends the contents of the variable user_name, and outputs that.

Appending a constant and a variable

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.

Tim Taylor

Figure 6. Tim Taylor

Got it? A variable is a piece of memory with a name. A constant is a fixed value. Text constants – often called string constants – have quotes around them. Single quotes will also work, like ‘CC’.

Back to “Hello world!”

Here’s the “Hello world!” program again.

$("#go").click(function() {
  //Get the user's name.
  user_name = $("#user_name_input").val();
  //Add it to the output.
  $("#user_name_output").text("Hello " + user_name + "!");
  //Show the output.
  $("#user_name_output").show('slow');
});

Figure 2 (again). Code

So, in line 5, "Hello " + user_name + "!" tells the browser to take the constant “Hello “, append the contents of the variable user_name, and append the constant “!”.

If user_name has Renata in it, the result would be Hello Renata! If user_name has Larry the crazy pickle in it, the result would be Hello Larry the crazy pickle!

What happens to that text? It’s inserted into the element with the id of user_name_output.

Don’t forget the #s in all of this. The code won’t work without them. Computers are picky.

Finally, line 7 shows the element with the id of user_name_output.

Exercise: First and last name

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

Can't find the 'comment' module! Was it selected?

What now?

On this page, you learned how to get some data from the user and show it. Let’s make a small change to improve a form’s usability.

Focus

Where are we?

You know how to show an input field, and get data from the user. Let’s improve the page’s usability.

This page’s goals

By the end of this page, you should know how to use focus() to improve a page’s usability.

A basic page

Please try this page. We’ll use it for this lesson and the next.

Here’s the code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Favorite Game</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#game_in").focus();
        $("#go").click(function() {
          user_game = $("#game_in").val();
          $("#game_out").text(user_game);
        });
      });
    </script>
  </head>
  <body>
    <h1>Favorite Game</h1>
    <p>Please enter the name of your favorite game 
    (e.g., fetch, frisbee, chewing shoes). Then click the button.</p>
    <p>Game: 
      <input type="text" id="game_in">
      <button type="button" id="go">Go</button>
    </p>
    <p>Favorite game: <span id="game_out"></span></p>
  </body>
</html>

Figure 1. Starting the game

Let’s look at the JS code:

<script type="text/javascript">
  $(document).ready(function() {
    $("#game_in").focus();
    $("#go").click(function() {
      user_game = $("#game_in").val();
      $("#game_out").text(user_game);
    });
  });
</script>

Figure 2. The JS code

Most of it is familiar. There’s ready(), click(), val(), and text(). But what’s that focus() in line 9? Line 9 is in the ready() event, so it runs when the page loads.

What’s focus()?

To see what focus() does, let’s look at another version of the page. It has the following code:

<script type="text/javascript">
  $(document).ready(function() {
//    $("#game_in").focus();
    $("#go").click(function() {
      user_game = $("#game_in").val();
      $("#game_out").text(user_game);
    });
  });
</script>

Figure 3. Modified JS code

In this version, I’ve commented out line 9. That’s the only difference.

OK, let’s compare them. Follow these instructions carefully. Don’t do anything extra. Not even a single click.

  1. Click this link to open the original page.
  2. Don’t click on anything. Just type “barking”.

You should see this:

With focus

Figure 4. With focus()

Now do this:

  1. Click this link to open the modified page.
  2. Don’t click on anything. Just type “barking”.

This is what you should see:

Without focus

Figure 5. Without focus()

Huh!? Where did the barking go?

It has to do with the focus. Watch this movie:

The Camtasia Studio video content presented here requires a more recent version of the Adobe Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

Figure 6. About focus()

Here’s the code again:

<script type="text/javascript">
  $(document).ready(function() {
    $("#game_in").focus();
    $("#go").click(function() {
      user_game = $("#game_in").val();
      $("#game_out").text(user_game);
    });
  });
</script>

Figure 2 (again). The JS code

Line 9 is bound to the ready() event. It runs when the page loads. It sets the focus to the input field, so the user is ready to type. Try the page, and you’ll see that the input cursor is in the field.

Without line 9, the user has to click on the field before s/he can type into it. If the user doesn’t click on the field, and just starts typing, the data is lost. The user’s keystrokes go somewhere, but not into the field.

Line 9 makes the page more usable. That is, it makes it easier for the user to do a task. Usability is important on the Web. Webers think about work flow, that is, the sequence of actions needed to do a task. If they can eliminate steps from the work flow, they will.

The thing we did in line 9 is common. Try going to Google’s home page. Where is the cursor?

Try going to Bing. Where is the cursor when the page loads?

Try Twitter. After you have logged in, where is the cursor?

We’ll talk more about usability as we go.

Exercise: Focus

Change your Hello world solution. When the page loads, the cursor should be in the first name.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

You learned how to use focus() to improve a page’s usability.

What now?

Let’s do some styling to change the look of input fields.

Styling input fields

Where are we?

You know how to show an input field, and get data from the user. Let’s improve the way things look.

This page’s goals

By the end of this page, you should:

  • Know how to change the look of a text field.
  • Know how to change the look of a button.

A plain page

Please try this page again. It’s the one we used in the previous lesson.

Here’s the code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Favorite Game</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#game_in").focus();
        $("#go").click(function() {
          user_game = $("#game_in").val();
          $("#game_out").text(user_game);
        });
      });
    </script>
  </head>
  <body>
    <h1>Favorite Game</h1>
    <p>Please enter the name of your favorite game 
    (e.g., fetch, frisbee, chewing shoes). Then click the button.</p>
    <p>Game: 
      <input type="text" id="game_in">
      <button type="button" id="go">Go</button>
    </p>
    <p>Favorite game: <span id="game_out"></span></p>
  </body>
</html>

Figure 1. Starting the game

The page is quite plain:

Plain page

Figure 2. Plain page

Let’s add some styling to create this:

Styled page

Figure 3. Styled page

You can try the page. Here’s the code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Favorite Game</title>
    <link type="text/css" rel="stylesheet" href="game2.css">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#game_in").focus();
        $("#go").click(function() {
          user_game = $("#game_in").val();
          $("#game_out").text(user_game);
        });
      });
    </script>
  </head>
  <body>
    <h1>Favorite Game</h1>
    <p>Please enter the name of your favorite game 
    (e.g., fetch, frisbee, chewing shoes). Then click the button.</p>
    <p>Game: 
      <input type="text" id="game_in" size="20">
      <button type="button" id="go">Go</button>
    </p>
    <p>Favorite game: <span id="game_out"></span></p>
  </body>
</html>

Figure 4. Styled page code

Line 23 uses the size attribute to set the width of the input field to 20 characters.

Including an external style sheet

But where are the styles? The background colors, the font changes, and such? There is no <style> tag in the file.

With JS, we saw that you can put your JS code in a separate file, and include it in your page. You can do the same thing with CSS: put the CSS rules in a separate file, and include them.

Here’s line 6:

<link type="text/css" rel="stylesheet" href="game2.css">

This tells the browser to include the CSS file game2.css.

Here’s the CSS file:

body {
  font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
  font-size: 18px;
  background-color: #FFFFF0;
}

h1 {
  font-size: 28px;
  font-weight: bold;
}

input {
  background-color: #FFFF80;
}

button {
  font-weight: bold;
  background-color: #006600;
  color: #FFFF40;
}

Figure 5. CSS file

The advantage is that you can reuse the same CSS across many HTML pages. Have one copy of the CSS file, and include it in all of the pages. Then, if you want to change, say, the background color of all of the HTML pages, change the one CSS file. Every HTML page that refers to the CSS looks different. W00f!

There’s not much new in the CSS rules themselves. Just the usual fonting and coloring. The only new things are on lines 12:

input {

and 16:

button {

They style all of the <input> and <button> tags on the page.

Notice how background-color works. It sets just the background color of the input fields and buttons.

input tag background color

Figure 6. <input> tag background color

Summary

You learned:

  • How to change the look of a text field.
  • How to change the look of a button.
  • How to include an external CSS file.

What now?

Let’s do some computations with data we get from users.

Doing computations

This page’s goals

On this page, you’ll learn how to do computations based on data users enter. We’ll review some of the things we did earlier, just to make sure you got it. Baby steps, baby steps.

You’ll learn:

  • How to show and hide content in response to user clicks.
  • How to change content using text().
  • How to show input fields to get data from users.
  • How to do computations on the data users enter.
  • How to delay showing the output area until computations are done.

Let’s roll!

Computing the tip

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.

CC
CC

The word “computation” sounds sort of scary.

Kieran
Kieran

Hmm, yes, I can see that. But all it means here is doing some arithmetic, multiplying and adding. Even better: the computer does the work! You don’t have to.

CC
CC

Hey, I like that!

Here’s my starting page. Everything except the computation.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <title>Tip</title>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#meal_cost").focus();
        $("#compute_tip").click(function(){
          alert("Tippy tip tip.");
        });
      });
    </script>
  </head>
  <body>
    <h1>Tip Computer</h1>
    <p>
      Meal cost: 
      <input type="text" id="meal_cost">
      <button type="button" id="compute_tip">Compute</button>
    </p>
    <p>Tip: <span id="tip"></span></p>
    <p>Total: <span id="total_cost"></span></p>
  </body>
</html>

Figure 1. Starting the tip computer

Please try the code so far.

Most of the code should be familiar. Line 20 creates a text field. Line 21 creates a button.

Line 23 creates an output area to show the tip. It introduces a new tag: <span>. <span> is an inline tag. It can be inserted right into the middle of some content. <span> lets us give an id to a spot on the page, so we can refer to that place in JavaScript code.

Line 24 is another output area. It also uses a <span> with, of course, a different id. Remember that ids should be unique within a page.

Let’s look at the JS.

$(document).ready(function() {
  $("#meal_cost").focus();
  $("#compute_tip").click(function(){
    alert("Tippy tip tip.");
  });
});

Figure 2. JavaScript from the first tip computer

Line 1 attaches some code to the ready() event. Lines 3 to 5 bind some code to the compute_tip button.

Line 2 sets the focus in the input field when the page loads. The user can start typing immediately. This makes the page more usable.

Now to do the computation. Here’s some JS (warning: there’s a bug):

$(document).ready(function() {
  $("#meal_cost").focus();
  $("#compute_tip").click(function(){
    //Get the cost of the meal.
    meal_cost = $("#meal_cost").val();
    //Compute the tip and total.
    tip = meal_cost * 0.15;
    total_cost = meal_cost + tip;
    //Output the results.
    $("#tip").text(tip);
    $("#total_cost").text(total_cost);
  });
});

Figure 3. Tip computer JS (broken)

Please try the code.

Line 5 gets whatever the user types into the input field and puts it into the variable meal_cost.

Line 7 works out the tip amount. * means “multiply,” so the line reads:

Take the contents of the variable meal_cost, multiply it by 0.15, and put the result in the variable tip.

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:

alt

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?

Buggy bug the buggity bug bugster

Welcome to the Wonderful World of Bugs.

The problem is that + has two meanings in JavaScript. The meanings are:

  • Add numbers together.
  • Append text together.

Earlier, we say code like this:

"Hello " + user_name + "!"

There’s that +. It meant:

Take the text “Hello “, append the contents of the variable user_name, and append the text “!”.

That’s what this line in Figure 3 is doing:

total_cost = meal_cost + tip;

JavaScript treats the contents of the variables mean_cost and tip as text rather than numbers. It’s taking the contents of the variable mean_cost, and appending the contents of the variable tip. So:

30 + 4.5 gives 304.5

This is stupid. Really stupid. That’s what computers are. Very, very, very stupid.

We want to tell JavaScript: “Dude, treat the contents of the variables mean_cost and tip as numbers.” Then it will add instead of appending.

You should always address a JavaScript program as “dude.”

Change the code to:

total_cost = parseFloat(meal_cost) + parseFloat(tip);

In computerese, a “float” is a kind of number. There are many kinds of numbers. For instance, an integer is a whole number. A float is a number that can have a fraction. The function parseFloat() tells JS to treat the stuff inside the () as a number that can have a fraction.

When you do this, the + becomes an add. Try it.

Exercise: Low tip

Change the program so it only tips 12%. Think anyone will notice?

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Kilos to pounds

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:

Page at start

Figure 1. Page at start

The user types a number in and clicks the button:

Page at start

Figure 2. Output

Upload your solution to your server, and put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Sharing the cost

Let’s change the program so that the bill is split evenly between more than one person. Please try this version.

Here’s the code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <title>Tip</title>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#meal_cost").focus();
        $("#compute_tip").click(function(){
          //Get the cost of the meal.
          meal_cost = $("#meal_cost").val();
          //Get the number of diners.
          humans = $("#humans").val();
          //Compute the tip and totals.
          tip = meal_cost * 0.15;
          total_cost = parseFloat(meal_cost) + parseFloat(tip);
          cost_per_human = total_cost / humans;
          //Output the results.
          $("#tip").text(tip);
          $("#total_cost").text(total_cost);
          $("#cost_per_human").text(cost_per_human);
        });
      });
    </script>
  </head>
  <body>
    <h1>Tip Computer</h1>
    <p>
      Meal cost: 
      <input type="text" id="meal_cost">
    </p>
    <p>
      Number of humans: 
      <input type="text" id="humans">
    </p>
    <p>
      <button type="button" id="compute_tip">Compute</button>
    </p>
    <p>Tip: <span id="tip"></span></p>
    <p>Total: <span id="total_cost"></span></p>
    <p>Cost per human: <span id="cost_per_human"></span></p>
  </body>
</html>

Figure 5. Group tip computer

There’s a new input field (line 35). The code is roughly the same. The total cost is divided up in line 18. There isn’t a parseFloat() in line 18, because the / operator only means “division.” So while + has two meanings, / only has one.

Exercise: Kilos and grams to pounds

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:

Page at start

Figure 1. Page at start

The user types numbers and clicks the button:

Page at start

Figure 2. Output

Hint: Use at least one parseFloat().

Upload your solution to your server, and put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Hiding the output area

When the page first loads, the output area looks a little strange. Just the headings, with no numbers.

It would be better if we could hide the output area at first, and show it after the user has entered the data and clicked the button.

The Camtasia Studio video content presented here requires a more recent version of the Adobe Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

Figure 6. Improving the interface

Let’s see how to do that. Please try the page.

We’ll change the HTML to this:

<div id="output_area">
  <p>Tip: <span id="tip"></span></p>
  <p>Total: <span id="total_cost"></span></p>
  <p>Cost per human: <span id="cost_per_human"></span></p>
</div>

Figure 7. Wrapping in a <div>

The output tags are wrapped in a new tag, <div>. Use <div> when you want to make a container, as we’ve done here. A container is a tag that has a bunch of other tags inside it.

If we do something to the <div>, we do something to all its contents as well. So, if we hide the <div>, we hide all of its contents. If we show the <div>, we show all its contents.

Here’s what we want to do:

  • When the page loads, hide the <div>.
  • When the user clicks the button, do the calculations, fill in the output fields, and then show the <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!

A little animation

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

Exercise: Kilos, grams, pounds, with animation

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:

Page at start

Figure 1. Page at start

No output area is shown.

The user types numbers and clicks the button:

Page at start

Figure 2. Output

The output appears with an animated effect.

Hint: Use at least one parseFloat().

Upload your solution to your server, and put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

You learned:

  • How to show and hide content in response to user clicks.
  • How to change content using text().
  • How to show input fields to get data from users.
  • How to do computations on the data users enter.
  • How to delay showing the output area until computations are done.

What’s next?

What happens when you make a mistake in your code? Time to talk about debugging.

Finding JavaScript bugs

Where are we?

You’re learning how to do some basic stuff with JavaScript. But what happens when your code doesn’t work?

This lesson’s goals

Learn:

  • Syntax bugs happen when you type something the browser doesn’t understand, like alrt().
  • Use Firefox’s error console to track down syntax errors.
  • Logic errors are when you tell the browser to do the wrong thing.
  • Use alert() statements to track program execution. If alert() messages are supposed to show up, but don’t, you know what code is not executing.
  • Use alert() statements to look at the values of variables.

Types of bugs

There are two types of errors:

  • Syntax bugs, where you give the browser an instruction it cannot understand.
  • Logic bugs, where you tell the browser to do the wrong thing.

The first type is easier to find and fix.

Syntax bugs

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.

Use the right editor

Up to now, you may have been using Notepad++. It’s a good editor to start with. Easy to use. It works just fine.

But it’s time to move on.

Install Netbeans, an integrated development environment (IDE). An IDE is a collection of tools to help people write code. The tools include an editor that, get this, checks for errors!

Here’s some code in Notepad++.

Code in Notepad++

Figure 1. Code in Notepad++

Looks OK. Here’s the same code in Netbeans.

Code in Netbeans

Figure 2. Code in Netbeans

Netbeans can analyze your code, and flag errors. This will save you a lot of time and frustration.

So, go to netbeans.org. Download the PHP bundle, and install it. Remember, the PHP bundle.

Netbeans is fairly easy to use, but there’s one hitch in getting started. Netbeans has the concept of projects, a collection of related files. You need to set up projects to work with Netbeans.

Don’t worry. It’s easy. Suppose you’ve been working on CoreDogs exercises. You created this in your Documents directory:

Your directories

Figure 3. Your directories

You’ve been putting your CoreDogs files in the CoreDogs directory:

Files in your directories

Figure 4. Files in your directories

You’ve been using Notepad++ to work on these files.

All you have to do is tell Netbeans to put your files into a project, and you’re ready to go. Let’s see how.

Here’s Netbeans without any projects.

Netbeans, empty

Figure 5. Netbeans, empty

Create a new project.

New project

Figure 6. New project

You’ll see a screen like this:

New project form

Figure 7. New project form

Tell it that you want to create a PHP project from existing sources:

Create a PHP project from existing sources

Figure 8. Create a PHP project from existing sources

Er, you installed the Netbeans PHP bundle, right?

PHP is a language for programs that run on Web servers. It’s covered in CoreDogs, in the ServerCore book.

The next Netbeans form is like this:

Name and location form

Figure 9. Name and location form

Select the directory you’ve been using for your exercises:

Select your directory

Figure 10. Select your directory

Click the Finish button. Netbeans will create your project.

Open the Sources, and you’ll see your files:

Your files in Netbeans

Figure 11. Your files in Netbeans

Double-click on a file to open it. Right click to create a new file:

Creating a new file

Figure 12. Creating a new file

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

Netbeans project subdirectory

Figure 13. Netbeans project subdirectory

Don’t delete it, or you’ll have to make the project again.

So, now you’re running Netbeans. There are other good IDEs, like Aptana.

These IDEs are good, but they’re not perfect. For example, check the code in Figure 2. There’s an error in the JavaScript that Netbeans didn’t flag as an error. The yellow in line 11 says that Netbeans thinks there might be something funny going on, but there’s no error icon.

You’ll need other tools to squash those bugs.

The error console

When a browser finds a syntax error in your JavaScript, it will do two things:

  • Stop running your code.
  • Tell you about the error. It will show an error message.

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:

Opening the error console

Figure 14. Opening the error console

Try it now. Your menu will look different, depending on the add-ons you have installed.

Here’s what I saw when I opened my error console just now:

The error console

Figure 15. The error console

Yikes!

Don’t panic. It’s normal to have a bunch of stuff showing.

You want to start with a clean slate, so you see error messages from your code, and not from other people’s pages. Click the Clear button. This erases all the messages.

OK. Now let’s load a page with an error, and see what happens. Here’s the code you’ll try to run:

$(document).ready(function() {
  alert("About to try a broken line of JavaScript.");
  alrt("This line is broken");
  alert("Just tried to run a broken line.");
});

Figure 16. Broken JavaScript

To try it, click on this link.

Now check the error console. This is what I see:

Error message

Figure 17. Error message

Sometimes it’s hard to know what an error message means. The browser doesn’t say, “Hey! You typed alert wrong.” Because it doesn’t know that. Maybe you really meant to type alrt, but forgot to tell the browser what alrt means. So you might have to think a bit to figure out what the problem is.

You can Google error messages, if you want. For example, you could search for:

javascript error “is not defined”

CC
CC

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.");

Kieran
Kieran

The line is right. But the browser stops as soon as it finds a syntax error. So it never gets to that line.

When error messages appear

The error message we just saw showed up as soon as the page was loaded. Why? Because the bad line was in the $(document).ready() event. Code there runs when the page loads.

Sometimes errors might not appear until later. Let’s try this one:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Broken again</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#button_of_doom").click(function(){
          alert("About to try a broken line of JavaScript.");
          alrt("This line is broken");
          alert("Just tried to run a broken line.");
        });
      });
    </script>
  </head>
  <body>
    <p>Click the button to make an error message.</p>
    <p>
      <button type="button" id="button_of_doom">Doom</button>
    </p>
  </body>
</html>

Figure 18. More broken JavaScript

The broken JS is line 11. This time, it’s inside the $("#button_of_doom").click() event. The browser won’t try to run line 11 until the button is clicked.

Let’s give it a try. First, clear the error console. Now click this link to load the page.

Check the error console. It should be empty. The browser hasn’t tried to run the bad line yet.

Click the button, and then the OK button on the dialog box that appears. Now check the error console again. There’s the error message.

So, if your JavaScript program isn’t running:

  • Open the error console and clear it.
  • Reload your page, and check the error console. This will show you syntax errors the browser found when it tried to load the page.
  • Do the thing that isn’t working right (e.g., click the button that’s supposed to do a calculation but doesn’t). Check the error console.

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.

CC
CC

Wow, finding bugs might be hard. Programming could get irritating.

Kieran
Kieran

Frustration is normal when doing computer work. You need ways of handling it. Know how to:

Or you could be like this guy.

The error console will help you fix syntax errors. Let’s move on to the second type of bug.

Logic bugs

Logic bugs are where the browser understands what you have told it, but you’ve told it the wrong thing. Sometimes these are just typing mistakes, but usually they’re thinking mistakes.

A problem with logic errors is that the browser won’t show an error message. The error console won’t help. You have to track down the error on your own.

Here’s a page with a simple logic error. You can try the page.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Square a Number</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#input_number").focus();
        $("compute_button").click(function() {
          input_number = $("#input_number").val();
          square = input_number * input_number;
          $("#square").text(square);
        });
      });
    </script>
  </head>
  <body>
    <h1>Square a Number</h1>
    <p>
      Type in a number, and I will tell you its square. For example,
      the square of 3 is 3 x 3 = 9.
    </p>
    <p>
      Number:
      <input type="input" id="input_number">
      <button type="button" id="compute_button">Compute</button>
    </p>
    <p>Square <span id="square"></span></p>
  </body>
</html>

Figure 19. Another broken page

See if you can find the problem by just looking through the code.

Don’t worry if you can’t spot the error. It’s easy to overlook, no matter how much you stare at the code.

alert()

One way to find errors is to add alert() statements, like this:

<script type="text/javascript">
  alert("Before the ready function");
  $(document).ready(function() {
    alert("Starting the ready function");
    $("#input_number").focus();
    $("compute_button").click(function() {
      alert("Starting the click function");
      input_number = $("#input_number").val();
      square = input_number * input_number;
      $("#square").text(square);
      alert("Ending the click function");
    });
    alert("Ending the ready function");
  });
</script>

Figure 20. Adding alert()s

I know when the alert dialogs should appear. I can run the page, and see whether what I expect to happen does happen. If it doesn’t, this will help me find the mistake.

Here’s when each alert dialog should appear:

  • Line 8: During page load, before any content appears.
  • Line 10: When the page loads and the content shows, but before the user can click on the button.
  • Line 19: Right after the dialog from line 10.
  • Line 13: After the user has clicked the button, but before any output has shown.
  • Line 17: After the output has been shown.

The Camtasia Studio video content presented here requires a more recent version of the Adobe Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

Figure 21. Tracking down the problem

You can try the page.

OK, so the page shows the alerts for lines 8, 10, and 19, but not for lines 13 or 19. Line 13 should show a message when the user clicks the compute button. Maybe the code for the compute button is not being run.

Here’s the code that sets up the click event for the button:

$("compute_button").click(function() {

Aha! I see the problem now. Do you see it?

Compare this line to the corresponding line from an example in the last lesson.

$("#compute_tip").click(function(){

I missed the #! The code should be:

$("#compute_button").click(function() {

Without the #, the browser can’t find the button to tie the event code to.

Renata
Renata

Wow, all that trouble because of one missing character?

Kieran
Kieran

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.

Showing variables

Sometimes that’s not enough. Here’s another version of the JS, with a different problem from the last one.

<script type="text/javascript">
$(document).ready(function() {
  $("#input_number").focus();
  $("#compute_button").click(function() {
    input_number = $("#input_number").val();
    square = input_number + input_number;
    $("#square").text(square);
  });
});
</script>

Figure 22. A different problem

Try the page. You get output this time, but it’s wrong:

Wrong output

Figure 23. Wrong output

If I add the same alert()s we had last time, I’ll find that everything appears just fine. All of the code is executing. But the output is wrong.

Hmm. Maybe I’ll check that the data is being read correctly, and the computations are done right.

I’ll add some more alerts:

<script type="text/javascript">
$(document).ready(function() {
  $("#input_number").focus();
  $("#compute_button").click(function() {
    alert("Starting the click function");
    input_number = $("#input_number").val();
    alert("input_number:" + input_number);
    square = input_number + input_number;
    alert("square:" + square);
    $("#square").text(square);
    alert("Ending the click function");
  });
});
</script>

Figure 24. alerts

Look at lines 12 and 13:

input_number = $("#input_number").val();
alert("input_number:" + input_number);

The alert() shows the value of a variable. I can compare it with what it should be.

Let’s run the code.

The Camtasia Studio video content presented here requires a more recent version of the Adobe Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

Figure 25. Showing variable values

You can try the page.

So, we know that this line is causing the problem:

square = input_number + input_number;

Aha! The + should be *! Change it, and the page will work.

W00f!

Exercise: Debugging JavaScript

Fix the bugs in this page.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Review your code

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.

Going deeper

Firebug is a debugging add-on for Firefox.

Summary

  • Syntax bugs happen when you type something the browser doesn’t understand, like alrt().
  • Use Firefox’s error console to track down syntax errors.
  • Logic errors are when you tell the browser to do the wrong thing.
  • Use alert() statements to track program execution. If alert messages are supposed to show up, but don’t, you know what code is not executing.
  • Use alert() statements to look at the values of variables.

What now?

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?

Renata and CC make a page

Where are we?

You’ve learned how to make pages that interact with the user. Renata and CC have been learning right along with you. Let’s see how they use their skills to make a page.

Today’s zombie score

Zombie

The dead have risen. Millions of them.

It’s just humans, of course. We dogs know better than to become zombies.

Your pack starts living in caves, going out for food as needed (MacDonalds and Burger King survived the apocalypse. Hmmm…). Wandering human zombies attack your foraging expeditions. Some of you hold each zombie down, and the rest chew its head off. Nasty, but it works.

There are three types of zombies: regular, wrestler, and geek. Wrestler zombies were professional wrestlers when they were alive. They’re tougher than regular zombies.

Geek humans became the toughest zombies of all. They’re hard to take down. You have to be very careful with geeks. Maybe because of their… say it with me… braaains.

You keep track of the zombies you rekill each day, and compute an overall daily score. You get one point for each regular zombie, five for a wrestler, and ten for a geek.

Write a Web page that lets the user enter the number of each type of zombie, and computes the total score.

Let me show you what your page should do.

You can try my solution.

OK, you two give it a try.

Renata
Renata

I guess that’s us.

CC
CC

Yep.

Renata
Renata

Well, we should, er… I don’t know how to get started.

CC
CC

Hmmm… Hey, how about we break the task up into pieces?

Renata
Renata

Makes sense. What’s the first piece?

CC
CC

Let’s start with what’s easy to do. The HTML isn’t complicated. Some text, a few fields. How about we do that first?

Renata
Renata

OK, good idea. When I create a new page, the first thing I do is copy the template we learned at the very beginning of ClientCore.

CC
CC

Works for me. I’ll make a new file in Netbeans and paste the HTML in.

 

<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>TITLE</title>
  </head>
  <body>
    BODY
  </body>
</html>

CC and Renata start with something they know works. They cut-and-paste from the HTML page template pattern.

Renata
Renata

OK, good. Now let’s add some HTML. Just a little to begin with.

[Type type]

CC
CC

Here it is.

 

<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Zombie Score</title>
  </head>
  <body>
    <h1>Zombie Score</h1>
  </body>
</html>
Renata
Renata

How’s that look in the browser?

CC
CC

Let’s see. I’ll open the file so far.

Renata
Renata

OK! Something showed up! W00f!

CC
CC

Yes! How about we do some CSS?

Renata
Renata

OK. Let’s do the background color.

CC
CC

Yes, but we need a color code. Hey, Kieran!

Kieran
Kieran

What’s up?

CC
CC

Can you give us the color code for the background?

Kieran
Kieran

Sure. Let me look at the source… OK, it’s FFFFEE.

CC
CC

Now we need to add this:

background-color: #FFFFEE;

Renata
Renata

You need to put that in the HTML CSS tag.

CC
CC

Oh, yes, that’s right. And does it get applied to the <body>?

Renata
Renata

Let me look at an example on CoreDogs… OK, you’re right.

CC
CC

Here’s the new page.

 

<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Zombie Score</title>
    <style type="text/css">
      body {
        background-color: #FFFFEE;
      }
    </style>
  </head>
  <body>
    <h1>Zombie Score</h1>
  </body>
</html>
CC
CC

Let’s have a look.

Renata
Renata

Cool!

CC and Renata take one small step at a time, and check their work as they go. This is easier than trying to create the entire page at once.

Renata
Renata

Hey, can I type in the font CSS?

CC
CC

Huh?

Renata
Renata

This is what we want it to look like:

What they want

This is what it looks like now:

What they have now

CC
CC

Oh, yes. Let’s take a look at that basic text styling pattern.

Why reinvent the wheel? Patterns make things easier.

Renata
Renata

Good idea. Hmm, let’s use Verdana. I like that. And text that’s 14 pixels. Makes it big enough to read. How’s this?

 

<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Zombie Score</title>
    <style type="text/css">
      body {
        background-color: #FFFFEE;
        font-family: Verdana, sans-serif;
        font-size: 14px;
      }
    </style>
  </head>
  <body>
    <h1>Zombie Score</h1>
  </body>
</html>
CC
CC

What’s the sans-serif on line 9 for?

Renata
Renata

If the computer doesn’t have the Verdana font, the browser will show a generic sans serif font.

CC
CC

Oh, yes, I remember that now. How’s it look?

Renata
Renata

Let’s check it out.

CC
CC

Nice! How about the instructions, you know, that say “Please enter the number” and so on.

Renata
Renata

Here we go. I’ll add the first field, as well. [Type type typity]

 

<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Zombie Score</title>
    <style type="text/css">
      body {
        background-color: #FFFFEE;
        font-family: Verdana, sans-serif;
        font-size: 14px;
      }
    </style>
  </head>
  <body>
    <h1>Zombie Score</h1>
    <p>Please enter the number of each type of zombie you
      rekilled today. Then click the Compute button.</p>
    <p>Regular:<br>
      <input type="text">
    </p>
  </body>
</html>
CC
CC

Hmmm. Is there something missing in the <input> on line 19?

Renata
Renata

What?

CC
CC

Let me look at CoreDogs… OK, you might need an id.

Renata
Renata

Why would we… Oh, OK, I remember. We need to give the <input> field an id, so when we get to the JavaScript, we can refer to the field. How about this?

<input type="text" id="regular">

CC
CC

That’s better. Let’s try it.

Renata
Renata

W00f! W00f!

CC
CC

Looking good! I’ll add the other input fields, and the button.

 

<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Zombie Score</title>
    <style type="text/css">
      body {
        background-color: #FFFFEE;
        font-family: Verdana, sans-serif;
        font-size: 14px;
      }
    </style>
  </head>
  <body>
    <h1>Zombie Score</h1>
    <p>Please enter the number of each type of zombie you
      rekilled today. Then click the Compute button.</p>
    <p>Regular:<br>
      <input type="text" id="regular">
    </p>
    <p>Wrestler:<br>
      <input type="text" id="wrestler">
    </p>
    <p>Geek:<br>
      <input type="text" id="geek">
    </p>
    <p>
      <button type="button" id="compute">Compute</button>
    </p>
  </body>
</html>

 

CC
CC

Let’s try it.

W00f! W00f! W00f!

Now for the dreaded JavaScript.

Renata
Renata

So how do we do it? I’m stuck.

CC
CC

Let’s trying breaking it down into pieces again, like we did with the HTML.

Renata
Renata

OK, we need to get the cursor in the first field when the program loads. Was there a pattern for that?

CC
CC

Let me check… You’re right, there is a pattern we can use. Let me copy the code and paste it in. Oh, and I need to make it put the cursor in the first input field.

Patterns to the rescue! Again!

[Type type type type]

Renata
Renata

Hey, wait a minute. Look at that code in Netbeans.

Error marker

CC
CC

Oh. That marker means Netbeans has found a problem, right?

Renata
Renata

Yes. It’s on the ). Maybe the opening ( is missing.

CC
CC

No, it’s there.

Ooo! Look! There’s a {, but no } later!

Error marker

Renata
Renata

You’re right! Add it, er, before the ).

CC
CC

Before it?

Renata
Renata

Yes, the ( is opened first, and then the {. Close the } first, and then the ). So they nest correctly.

CC
CC

Oh, I get it. [Type type]

Error gone

W00f! That was it!

Smart editors like Netbeans find some errors for you. This will save you time. And frustration.

OK. Here’s all the code so far.

 

<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Zombie Score</title>
    <style type="text/css">
      body {
        background-color: #FFFFEE;
        font-family: Verdana, sans-serif;
        font-size: 14px;
      }
    </style>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#regular").focus();
      });
    </script>
  </head>
  <body>
    <h1>Zombie Score</h1>
    <p>Please enter the number of each type of zombie you
      rekilled today. Then click the Compute button.</p>
    <p>Regular:<br>
      <input type="text" id="regular">
    </p>
    <p>Wrestler:<br>
      <input type="text" id="wrestler">
    </p>
    <p>Geek:<br>
      <input type="text" id="geek">
    </p>
    <p>
      <button type="button" id="compute">Compute</button>
    </p>
  </body>
</html>
CC
CC

Let’s give it a try.

Renata
Renata

Er, the cursor isn’t in the first field. Why didn’t it work?

CC
CC

I don’t know. What do we do now?

Renata
Renata

Let’s look through the code again.

(Five minutes pass…)

CC
CC

I didn’t see anything wrong.

Renata
Renata

Me neither. Hey, let’s look at the error console. You know, that we learned about in the debugging lesson?

CC
CC

OK. I’ll bring it up.

Firefox error console

Renata
Renata

Look, right at the bottom. “$ is not defined.” We’ve used $ before. Why is it breaking now?

CC
CC

(Sigh) I don’t know. Let’s ask the pack leader. Er, Kieran?

Kieran
Kieran

What’s up?

CC
CC

What’s the error message “$ is not defined” mean?

Kieran
Kieran

Oh, that one. You know the HTML page template pattern?

Renata
Renata

Yes.

Kieran
Kieran

Look at the section on JavaScript and jQuery. See if there’s anything missing on your page.

CC
CC

OK. Let’s take a look at the pattern

Renata
Renata

Oh! There! We forgot the line that loads jQuery!

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

I’ll cut-and-paste it. [Click click type type]. OK, now let’s see what we have.

Use the error console to see if the browser found errors in your code. If you see the error “$ is not defined” in the error console, make sure you have loaded jQuery.

CC
CC

W00f! W00f! W00f!

Check that you are using the right pattern for the situation. CC and Renata should have started with the “Web page with JavaScript and jQuery” pattern, not just the “Web page” pattern.

Renata
Renata

Now what?

CC
CC

I’m not sure. Hmmm… Let’s look at the pattern list. Maybe we’ll see something useful.

Renata
Renata

Here’s one, Run code on click. We want to do something when the button is clicked.

CC
CC

OK. Let’s take a look… Oh, OK. I’ll change the code.

 

<script type="text/javascript">
  $(document).ready(function() {
  $("#regular").focus();
    $("compute").click(function() {
    });
 });
</script>
Renata
Renata

How will we know whether it worked?

CC
CC

Hmmm. Oh, look at this in the pattern. An alert. We can do that. I’ll change it to:

 

<script type="text/javascript">
  $(document).ready(function() {
  $("#regular").focus();
    $("compute").click(function() {
      alert('Clicked');
    });
 });
</script>

So we should see the message “Clicked” when we click on the button.

Renata
Renata

Great! Let’s give it a try.

CC
CC

Oh, come on, you stupid machine! Why didn’t you work?

Renata
Renata

Check the error console.

CC
CC

OK… Nothing new.

Renata
Renata

(Sigh) Let me eyeball the code… Hey! It might be this. Look at the these two lines:

$("#regular").focus();
$("compute").click(function() {

CC
CC

I see them. So what?

Renata
Renata

We forgot the # in front of compute.

CC
CC

ACK! You’re right. The # means “look for an something with an id of compute.” Without it, jQuery won’t find the button.

This is a common mistake.

CC
CC

I’ll put it in:

$("#regular").focus();
$("#compute").click(function() {

Now let’s try it.

W00f! W00f! W00f! W00f!

Renata
Renata

W00f! W00f!

Now what?

CC
CC

OK, the user presses the button. What should our page do?

Renata
Renata

Let’s think it through. At the end, we want to show the total score. One point for regular zombies, five for wrestlers, and ten for geeks. Something like this:

score = regular + wrestlers x 5 + geeks x 10

CC
CC

Oh, OK. Let me try something. When the user clicks the button, the code should do this:

Get numbers from the fields (what the user typed).
Compute the score.
Show the score.

Renata
Renata

Yes, that’s it. That’s looks like the Input-process-output pattern. Get the input, do something with it, and show the output.

CC
CC

Alright, we’re getting somewhere. Let’s get the three numbers. Here’s what we have so far:

 

<script type="text/javascript">
  $(document).ready(function() {
  $("#regular").focus();
    $("compute").click(function() {
      alert('Clicked');
    });
 });
</script>
CC
CC

Let’s start by getting rid of that alert.

Renata
Renata

Wait a minute, I’ve got an idea. Leave it in there. Let’s get whatever the user typed into the first input field, and use the alert to show it.

Smart Renata! One small step at a time. Then check that it works.

CC
CC

Here, you take the keyboard. It’s fortunate we have a keyboard that’s good for dogs. Have you seen the tiny keys on the humans’ keyboards? Nasty.

Renata
Renata

Let’s see. How about this?

 

<script type="text/javascript">
  $(document).ready(function() {
  $("#regular").focus();
    $("compute").click(function() {
      regular = $("regular").val();
      alert(regular);
    });
 });
</script>
CC
CC

You forgot the # in line 5.

Renata
Renata

Oh, yes. Here.

 

<script type="text/javascript">
  $(document).ready(function() {
  $("#regular").focus();
    $("compute").click(function() {
      regular = $("#regular").val();
      alert(regular);
    });
 });
</script>

Let’s try it.

W00f! It worked!

CC
CC

Now do the other two fields.

Renata
Renata

OK! [Type type type type]

 

<script type="text/javascript">
  $(document).ready(function() {
  $("#regular").focus();
    $("compute").click(function() {
      regular = $("#regular").val();
      alert(regular);
      wrestler = $("#wrestler").val();
      alert(wrestler);
      geek = $("#geek").val();
      alert(geek);
    });
 });
</script>

Let’s try it.

CC
CC

Yes! W00f! W0000f! Resistance is futile, computer!

Renata
Renata

W00f!

Let’s go back to the three steps.

Get numbers from the fields (what the user typed).
Compute the score.
Show the score.

We’ve done the first one. Now for the second. Compute the score. [Type type]

 

<script type="text/javascript">
  $(document).ready(function() {
  $("#regular").focus();
    $("compute").click(function() {
      regular = $("#regular").val();
      alert(regular);
      wrestler = $("#wrestler").val();
      alert(wrestler);
      geek = $("#geek").val();
      alert(geek);
      score = regular + 5 * wrestler + 10 * geek;
      alert(score);
    });
 });
</script>

How’s it look?

CC
CC

Great! Let’s give it a try. I’ll type 1, 2, and 3 in the fields.

Bad score

Renata
Renata

You’ve got to be kidding me.

CC
CC

A-R-G-H!!

(Depressed silence)

CC
CC

Hey, wait a minute. Didn’t we see something like this before? When JavaScript was getting the math wrong?

Renata
Renata

Hmmm, yes, we did. Wasn’t it just a couple of lessons ago?

CC
CC

Here it is! We need to tell JavaScript to treat what it gets from the input fields as numbers. With that parseFloat thing.

Renata
Renata

Oh, yes, that’s right! We need to put parseFloat() around everything we get from the user, at least everything that we want to be a number. But I’m not sure exactly what to type.

CC
CC

Me neither, but I’ve got something I want to try. [Type type type type type type]

 

<script type="text/javascript">
  $(document).ready(function() {
  $("#regular").focus();
    $("compute").click(function() {
      regular = $("#regular").val();
      alert(regular);
      wrestler = $("#wrestler").val();
      alert(wrestler);
      geek = $("#geek").val();
      alert(geek);
      score = parseFloat(regular) + 5 * parseFloat(wrestler) + 10 * parseFloat(geek);
      alert(score);
    });
 });
</script>
Renata
Renata

Do you need all three of those parseFloats on line 11?

CC
CC

I don’t know. But let’s give it a try. I’ll type 1, 2, and 3 in the fields again.

Renata
Renata

W00f! W00f! W00f! W00f! W00f!

CC
CC

We’ve got it! Now we have the first two parts of:

Get numbers from the fields (what the user typed).
Compute the score.
Show the score.

Renata
Renata

We’ve done the last one, too. We’ve shown the score.

CC
CC

Not in the right way. Look at the movie again.

Renata
Renata

Oh, yes. We need to put the score on the page, and show it. Let’s see if there’s a pattern for that.

How about this one? Change text on the page.

CC
CC

Looks good. First we need the output area.

Let’s do this. I’ll remove the alerts, too. [Type type]

 

$("#compute").click(function(){
  regular = $("#regular").val();
  wrestler = $("#wrestler").val();
  geek = $("#geek").val();
  score = parseFloat(regular) + 5 * parseFloat(wrestler) + 10 * parseFloat(geek);
  $("#score").text(score);
});
...
<p>
  <button type="button" id="compute">Compute</button>
</p>
<p>
  Score: <span id="score"></span>
</p>

Let’s try it.

Renata
Renata

W00f! W00f! We’re almost done. I found this pattern that hides output areas until they’re needed. Give me that keyboard. [Type type type type type]

 

$(document).ready(function() {
  $("#output_area").hide();
  $("#regular").focus();
  $("#compute").click(function() {
    regular = $("#regular").val();
    wrestler = $("#wrestler").val();
    geek = $("#geek").val();
    score = parseFloat(regular) + 5 * parseFloat(wrestler) + 10 * parseFloat(geek);
    $("#score").text(score);
    $("#output_area").show('fast');
  });
});

...
<p>
  <button type="button" id="compute">Compute</button>
</p>
<p id="output_area">
  Score: <span id="score"></span>
</p>

On line 18, I gave the output area an id. Then when the page loads, line 2 hides the entire output area.

The score is computed, and put into the output on line 9. Then line 10 shows the entire output area.

Now, for the big test!

Renata
Renata

It worked! W00f! W00f! W00f!

CC
CC

W00f! W00f! W00f! W00f! W00f!

Kieran
Kieran

How’s it going?

Renata
Renata

We got it! W00f! W00f!

Kieran
Kieran

Good job! W00f!

CC
CC

Coffee time?

Renata
Renata

And a nice dog biscuit. Let’s go!

Summary

Renata and CC created a page. They started with a template they knew worked. Then they went step by baby step, adding something and then checking that it worked. They used the alert statement to help.

Renata and CC used patterns a lot. They went back to the pattern library again and again.

They used Netbeans, a smart editor. It marked errors it found.

You should use the same habits in your own work.

What now?

Let’s see how you can add a quiz about yourself to your eMe.

eMe: A quiz

Where are we?

You know quite a lot now. You know some events, and how to do things when the events fire. Let’s put that knowledge to use on your eMe site.

A quiz about you

Make a quiz, with at least five questions. You can try mine (though it has fewer questions).

Make a quiz about something on your interesting stuff list. If you can’t think of anything, make a quiz about yourself. Where you were born, when, like that.

The quiz will be based on the one we did earlier. It looked like this:

Earlier quiz

Figure 1. Earlier quiz

Here are the important bits from the code:

<script type="text/javascript">
  $(document).ready(function() {
    $(".right").click(function() {
      $("#result").text("Right! W00f!");
    });
    $(".wrong").click(function() {
      $("#result").text("Sorry, that's wrong.");
    });
  });
</script>
...
<p>What is 4 x 7?</p>
<p>Please click on the right answer.</p>
<p class="wrong">a. 14</p>
<p class="wrong">b. 47</p>
<p class="right">c. 28</p>
<p class="wrong">d. I will never need to know.</p>
<p id="result"></p>

Figure 2. Quiz starting code

Look at the HTML. In lines 14 to 17, each response is given a class of right or wrong. Line 18 is where we show the result of a click, that is, the “You’re right” or “You’re wrong” message. It has an id of result.

Line 4 shows what happens when the user clicks on the right answer (that is, something with the class of right):

$("#result").text("Right! W00f!");

This says:

Find the element with an id of result, and put the text “Right! W00f!” in it.

Multiple questions

In the new quiz, we have more than one question. That means more than one set of answers, and more than one result area.

Quiz

Figure 3. Quiz

There are two questions in Figure 3. Each one has its own set of answers, and result area.

When the user clicks an answer, the page should change only the matching result area.

Separate events

Figure 4. Separate events

There are many ways to do this. We’ll talk about one that’s easy to understand.

We have to be able to refer to each result area separately. So we’ll give each one a different id. We also need to separate the answers for each question, so we can’t use just two classes, right and wrong. Instead, we’ll create separate right and wrong classes for each question.

Here’s the HTML we’ll use.

<h2>Q 1. When was I born?</h2>
<p class="q1_right">a. 1960</p>
<p class="q1_wrong">b. 1975</p>
<p class="q1_wrong">c. 1985</p>
<p class="q1_wrong">d. I was hatched, not born.</p>
<p id="q1_result" class="result"></p>

<h2>Q 2. What was the first programming language I learned?</h2>
<p class="q2_wrong">a. Java</p>
<p class="q2_wrong">b. JavaScript</p>
<p class="q2_wrong">c. C</p>
<p class="q2_right">d. FORTRAN</p>
<p id="q2_result" class="result"></p>

<h2>Q 3. What is the hex opcode for the Halt instruction on a Z80?</h2>
<p class="q3_wrong">a. CD</p>
<p class="q3_wrong">b. C9</p>
<p class="q3_right">c. 76</p>
<p class="q3_wrong">d. 20</p>
<p id="q3_result" class="result"></p>

Figure 5. HTML for multi-question quiz

Have a look at the result sections, in lines 6, 13, and 20:

<p id="q1_result" class="result"></p>

<p id="q2_result" class="result"></p>

<p id="q3_result" class="result"></p>

Each one has a different id. But we want to style them all the same way, so we give them the same class.

Here’s the code for one of the questions:

<h2>Q 1. When was I born?</h2>
<p class="q1_right">a. 1960</p>
<p class="q1_wrong">b. 1975</p>
<p class="q1_wrong">c. 1985</p>
<p class="q1_wrong">d. I was hatched, not born.</p>
<p id="q1_result" class="result"></p>

Figure 6. HTML for one question

Click on an item with a class of q1_right or q1_wrong, and the text of q1_result should change.

The other questions follow the same pattern:

<h2>Q 2. What was the first programming language I learned?</h2>
<p class="q2_wrong">a. Java</p>
<p class="q2_wrong">b. JavaScript</p>
<p class="q2_wrong">c. C</p>
<p class="q2_right">d. FORTRAN</p>
<p id="q2_result" class="result"></p>

Figure 7. HTML for the another question

Click on an item with a class of q2_right or q2_wrong, and the text of q2_result should change.

Here’s the JavaScript:

$(document).ready(function() {
  $(".q1_right").click(function() {
    $("#q1_result").text("Right! I was born in 1960.");
  });
  $(".q1_wrong").click(function() {
    $("#q1_result").text("Sorry, that's not it.");
  });
  $(".q2_right").click(function() {
    $("#q2_result").text("Right! The first programming language I learned was FORTRAN.");
  });
  $(".q2_wrong").click(function() {
    $("#q2_result").text("Sorry, that's not it.");
  });
  $(".q3_right").click(function() {
    $("#q3_result").text("Right! The Halt instruction on a Z80 is 76 hex.");
  });
  $(".q3_wrong").click(function() {
    $("#q3_result").text("Sorry, that's not it.");
  });
});

Figure 8. Quiz code

The first event handler is:

$(".q1_right").click(function() {
   $("#q1_result").text("Right! I was born in 1960.");
});

So, clicking on something with a class of q1_right changes the text in q1_result. Notice that it’s $(".q1_right") and not $("#q1_right"). Use a . for a class, and a # for an id.

Let’s make an exercise for all this.

eMe: A quiz about you

Make a quiz, with at least five questions.

Use the same styles you created for the text pages with external styles exercise. (You can copy the entire .css file, if you want).

Upload your solution to your server. Put the result below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

In this lesson, you created an interactive quiz. How cool is that? You are mastering some cool skills.

What now?

Users often make mistakes when they type data into forms. Like giving their year of birth as 1880, instead of 1980. Let’s see how you handle errors like that.

Validation

Where are we?

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.

This lesson’s goals

By the end of this lesson, you should:

  • Know how to check whether a field has a value.
  • Know how to check whether a number is OK.

Is something there?

Let’s start with this page:

Age

Figure 1. Age

If the user clicks the button without entering anything, this is what happens:

Age is empty

Figure 2. Age is empty

Here’s the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Check age 1</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style type="text/css">
      body {
        font-family: Verdana, sans-serif;
        font-size: 14px;
        background-color: #FFFFE0;
      }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#age").focus();
        $("#go").click(function(){
          age = $("#age").val();
          if ( age == "" ) {
            alert("Please enter your age.");
          }
        });
      });
    </script>
  </head>
  <body>
    <h1>Check age 1</h1>
    <p>
      Age:
      <input type="text" id="age" size="3">
    </p>
    <p>
      <button type="button" id="go">Go</button>
    </p>
  </body>
</html>

Figure 3. Age checker

You can try it.

The action starts on line 18:

age = $("#age").val();
if ( age == "" ) {
  alert("Please enter your age.");
}

Part of Figure 3. Age checker

Line 18 gets the value that the user typed, and puts it into the variable age.

The next line has an if statement. This is what does the check. The general form of an if statement is:

if ( test ) {
  Do this if the test is true.
}

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!

Exercise: Favorite animal

Write a page that looks like this:

Favorite animal

Figure 1. Favorite animal

If the user clicks the button without typing anything, show a message:

No favorite animal

Figure 2. No favorite animal

Upload your solution to your server and put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

true code and false code

You can also tell the browser what to do when the test is false:

if ( test ) {
  Do this if the test is true.
}
else {
  Do this if the test is false.
}

Let’s use this in the age checker.

age = $("#age").val();
if ( age == "" ) {
  alert("Please enter your age.");
}
else {
  alert("Thank you!");
}

Figure 4. Age checker junior

Exercise: Favorite animal again

Change your previous page so that it thanks the user if s/he puts something in the field. Like this:

Thank the user

Figure 1. Thank the user

Upload your solution and put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

You can include as many statements as you like between the braces of an if statement. For example, you could do this:

age = $("#age").val();
if ( age == "" ) {
  alert("Please enter your age.");
}
else {
  double_age = age*2;
  alert("In " + age + " years, you will be " + double_age + ".");
  alert("Last year, you were " + (age - 1) + ".");
}

Figure 5. Age checker III

You can try it.

Exercise: Favorite animal again, again

Change your favorite animal page. If the user enters nothing, it shows two messages. The first one should be:

First message

Figure 1. First message

When the user clicks the button, a second message shows:

First message

Figure 2. Second message

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

if this and if that

Often you want to chain if statements together. Here’s an example.

age = $("#age").val();
if ( age == "" ) {
  alert("Please enter your age.");
}
else if ( isNaN(age) ) {
  alert("Please enter a number.");
}
else if ( age < 21 ) {
  alert("Sorry, you are too young.");
}
else {
  alert("Thank you!");
}

Figure 6. Yet another age checker

Just one of the alert()s above will be shown. You can try it.

There are some other new things here. Here’s line 22:

else if ( isNaN(age) ) {

isNaN(age) is true if age is Not A Number. You have to get the name right when you type the function. So isnan, IsNaN, and isNAN are all incorrect.

Here’s line 25:

else if ( age < 21 ) {

This is true if age is less than 21.

Here are some other comparisons you can do:

== is equal to
!= is not equal to
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to

Figure 7. Comparison operators

You can check text strings as well. For example:

if ( age == "old" ) {
   alert("You don't look old.");
}

Exercise: Math quiz

Create a page that asks the user to answer a math question:

Math quiz

Figure 1. Math quiz

Show an alert() like this:

Math quiz response

Figure 2. Math quiz response

Here are the rules for the alert()s:

  • If the field is empty, show “Please enter your answer.”
  • If the field doesn’t contain a number, show “Please enter a number.”
  • If the field is less than 14, show “Sorry, that is too low.”
  • If the field is more than 14, show “Sorry, that is too high.”
  • If the field is 14, show “You got it right!.”

Upload your solution to your server, and put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

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:

  • Check whether a field has a value.
  • Check whether a number is OK.

What now?

Wow! That was one of the most complicated lessons so far. But you will use the things you’ve learned again and again.

Exercises: A Web page that interacts

You should do the four recommended exercises. Do the optional exercises if you want more practice.

Exercises in the Explore section are more challenging. You may need to use HTML and CSS that isn’t covered in CoreDogs. Get ready to Google!

Recommended

Exercise: Inversion 1

The invert of a number is 1 divided by that number. So the invert of 2 is 1/2 = 0.5. The invert of 3 is 1/3 = 0.333. The invert of 82.8 is, er, something or other.

Write a program that inverts a number that the user enters.

Upload the solution to your server, and put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Hypotenuse

Write a JavaScript program to compute the length of the hypotenuse of a right triangle from the length of the other two sides.

The formula is:

hyp = Math.sqrt(c1*c1 + c2*c2);

Hypotenuse

(Image from Wikipedia)

Upload your solution to your server, and paste the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Clowns among us

Paula is an accountant clown. No, really. Companies hire her to do her shtick at board meetings. You can just imagine how funny it is. You’ll have to, because I can’t bear to describe it.

Paula has a pay-by-performance policy. The more laughs she gets, the more she gets paid. She charges:

  • $0.80 for each guffaw
  • $1.10 for each belly laugh

For example, suppose there were 20 people at a board meeting. Paula does her act. On average, each person guffawed 8 times, and had 5 belly laughs. So:

Revenue per person = 0.80 × 8 + 1.10 × 5 = $11.90

Total revenue = $11.90 × 20 = $238

Paula has a hard time with numbers. Write a Web page to help her estimate how much she will earn for a gig.

The page starts off like this:

Page after loading

Figure 1. Page after loading

I made my browser narrow to get the screenshot. Your page does not have to break between Estimatronical and Numeratoid. It can all be on one line.

Notice that the cursor is in the first input field when the page loads. The color codes are #7C8B9B and #E5EBDF.

Paula fills in some numbers and clicks the button:

Page after computations

Figure 2. Page after computations

The output appears only after the button has been clicked.

Notice that the cursor has gone back to the first input field.

Upload your page, and enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Cute animals

Create a page that looks like this when it first loads:

Page at the start

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

Here’s what the page looks like after the first click:

After first click

Here’s what it looks like at the end:

Page at the end

You can watch a video showing how the interaction should work.

Match the colors approximately. Use any sans serif font. Use at least two CSS classes (you can use more).

I made my browser narrow to make the screenshot above, so I could fit it in this page. You don’t need to have the same width.

Hints:

  • The animal names start off with a CSS class.
  • Hide the output stuff when the program loads. Show it when there’s a click.
  • It’s OK if the user clicks on each animal name more than once. For an extra challenge, figure out how to prevent that. Hint: can you disable the click event?

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Optional

Exercise: Circumference 1

Write a JavaScript program to compute the circumference of a circle from the diameter. The user types in the diameter, clicks a button, and the program shows the circumference.

The formula is:

circumference = diameter * pi

pi is around 3.14159.

JavaScript has the value of pi built-in. If you want to try it, use Math.PI instead of 3.14159.

Upload your solution to your server, and paste the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Circumference and area 1

Write a JavaScript program that reports the circumference and area of a circle. The user types in the diameter, and clicks a button.

The formula is:

area = pi * diameter/2 * diameter/2

Upload your solution to your server, and past the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Order beans and things

Make a page with an order form like this:

Empty order form

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:

Empty field

Figure 2. Empty field

Show an error message is a field has an invalid number:

Bad number

Figure 3. Bad number

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

Number 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:

Data OK

Figure 5. Data OK

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Vampire fighters

Create a page to compare the performance of two vampire fighters: KM and MS. The page starts like this:

Page after loading

Figure 1. Page after loading

I made my browser narrow to get the screenshot. Your page does not have to break between Compute and winner. It can all be on one line.

Notice that the cursor is in the first input field when the page loads. The color codes are #7C8B9B and #E5EBDF.

The user fills in some numbers. Here’s what it looks like after some input, but before the button is clicked:

Input

Figure 2. Page after input

When the clicks the button, do these things:

  • Change MS’s score to one less than KM’s score. So if KM had 5, the text field for MS would change to 4. It doesn’t matter what score MS has.
  • Show a message that KM wins, and Buffy likes KM better.

Here’s what the display would look like after the button is clicked with the data above:

Page after computations

Figure 3. Page after click

Notes:

  • You don’t need to validate the input. You can assume that the user always types valid numbers.
  • The final output is the always the same. KM always wins.
  • Use whatever sans serif typeface you like, in whatever sizes you like.
  • Notice the color and size of the output messages. Match them approximately.
  • After the user clicks the button, the cursor goes back to the first input field.
  • Hint: $("#thing").val(13) would set the value of the form field thing to 13.

Upload your page to your server, and put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Cake order

Write a page that takes an order for a cake. The user makes three choices:

  • The size of the cake – small, medium, or large.
  • The flavor of the cake – chocolate or vanilla.
  • The flavor of the frosting – chocolate or vanilla.

The page looks like this when it opens:

Page when it opens

Figure 1. Page when it opens

When the user puts the mouse cursor over any <li> element, the cursor changes to a hand:

Cursor

Figure 2. Cursor

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

Selecting a cake option

Figure 3. Selecting a cake option

The output area has one part for each category of choices: size, cake flavor, and frosting flavor. When the user clicks on a cake size, his/her choice appears in the size part of the output area. And so on.

Once the user has clicked on a choice within a category, s/he can still change his/her mind. If the user clicks on a different choice, the new choice is shown in the output area:

Selecting a different cake option

Figure 4. Selecting a different cake option

The user can select one option in each category. For example:

A complete order

Figure 5. A complete order

Finally, the user clicks the Order button, and an alert() message appears:

Order button clicked

Figure 6. Order button clicked

Upload your solution to your server.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Advanced exercise

Exercise: Estimating order quantity

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

Inventory over time

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:

Fields without data

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

Policy hidden

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

Policy shown

Click again, and the policy hides.

The user fills in the values. For example:

Fields with data

Clicking the button shows the results:

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:

  • When the page first loads, put the cursor into the product name field.
  • Make the output look nicer. For example, round the order quantity to the nearest whole number. (You’ll need to do some Googling to find out how to do this.)
  • Output the date of the analysis. (You’ll need to do some Googling to find out how to do this.)

Upload your solution to your server. Enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Explore

These challenging exercises may use HTML not covered in CoreDogs. Get ready to Google!

Exercise: Show and hide text

Make a page that hides detailed information until the user asks for it. My page is about dogs, but you can make yours about something else.

The page starts out like this:

Page at start

Figure 1. Page at start

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

After a click

Figure 2. After a click

Click on the same title again, and (1) the arrow changes back into a down arrow, and (2) the text disappears.

Use an animated effect to show and hide the text.

Here’s some code that might help:

<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    ...
    <script type="text/javascript">
      $(document).ready(function() {
          $(????).click(function() {
            //Is it already visible?
            if ( ????.is(":visible") ) {
              //Visible - hide it.
              ????.hide(????);
              ????.html("↓");
            }
            else {
              //Not visible - show it.
              ...
            }
          });
          ...
      });
    </script>
  </head>
  <body>
    ...
    <p id="????"><span id="????">↓</span> Domestication</p>
    <p id="????">
      Dogs were domesticated from gray wolves about 15,000 years ago.
      ...
    </p>
    ...
  </body>
</html>

You don’t have to use this code if you don’t want to.

Upload your solution to your server, and put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Guess the number - 1

Make a page for a number guessing game. The page starts out like this:

Page at start

Note that the cursor is in the text field.

The user enters a guess, and clicks the button. If the value the user entered is not a number, show an error message. Otherwise, the page changes to one of these:

Too low

Too high

Right

After each guess, the cursor goes back into the text field.

Here’s some code that might help:

<script type="text/javascript">
  //Declare variable outside ready(), so its value is kept between guesses.
  var right_answer;
  $(document).ready(function() {
    right_answer = parseInt(Math.random() * 100) + 1;
    ...
    $("#guess_button").click(function() {
      var guess = $("#guess").val();
      if ( ???? ) {
        alert('Please enter a number.');
      }
      else {
        ...
      }
      ...
    });
  });
</script>

You don’t have to use this code if you don’t want to.

Upload your solution to your server, and put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Guess the number - 2

Change the game in two ways:

  • Add a button that starts a new game.
  • Show the number of guesses the user has made in this game.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

A page with images

Images are very important on the Web. They help explain things.

Pixels
Like what pixels are.

Images also help set a mood.

Puppy
How cute is this?

The Web wouldn’t be the Web without images.

You need to know how to use images. Not only how to insert them in HTML. But also where to get images, how to change them, and, most important, what they’re for.

That’s what this lesson is about.

You’ll also learn how to manipulate images with jQuery. This is Much Fun. You’ll show images, hide them, resize them, all with animated effects.

Finally, you’ll learn more about 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:

Onward! To destiny!

What images are for

This page’s goals

By the end of this page, you should:

  • Know what an informational image is.
  • Know what an interface image is.
  • Know what a structural image is.
  • Know the difference between a good image and a bad one.
  • Know what basic image skills you need for Web work.

What are images for?

Images serve three main purposes: informational, interface, and structural. These are not completely separate categories. Some images have multiple functions.

Informational images

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.

Bulldog

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:

Whisk

The photo contributes to the content, that is, it helps people understand how to make dog biscuits.

CC
CC

Er, won’t everyone know what a whisk is?

Kieran
Kieran

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.

Renata
Renata

Where did you get that photo?

Kieran
Kieran

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.

Awwwww

How you can look at that and not go, “Awwww…”

Interface images

Users click, drag, or otherwise interact with interface images. Here are some buttons:

Button

Button

Button

Button

Structural images

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

Dividers break up sections of a page.

Divider

Divider

Divider

Divider

Bullets

Bullets are often used with list items.

Bullet

Bullet

Bullet

Bullet

Banners

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

Banner

Banner

Banner

Banner

Are some images better than others?

You need to know what images to use when. Here are some guidelines.

Utility

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.

Small map

Mood

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

Curious?

Colors

The palette of each image should match the color scheme of your site. We’ll talk more about color later in this chapter.

Screen size

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.

File size

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.

Working with images

Every Weber needs to know how to do some basic image tasks.

  • Resize an image.
  • Crop an image.
  • Compress an image.
  • Add text to a photo, with anti-aliasing.
  • Manage an image collection.
  • Create simple drawings.
  • Take screen shots.

We’ll talk about these tasks later.

You should also consider learning how to:

  • Cut out objects from images.
  • Apply filters, like drop shadow and blur.
  • Fix artifacts in photos with dodge and burn.
  • Use layers to combine image objects.
  • Use connectors in drawings.
  • Use a Bézier tool.

Most images on the Web are simple. You can make almost all the images in an entire site with just a few basic skills.

Summary

On this page, you learned:

  • What an informational image is.
  • What an interface image is.
  • What a structural image is.
  • The attributes of good images.
  • What basic image skills you need for Web work.

What now?

Let’s start by exploring how computers show images.

How computers show images

Where are we?

You know that it’s important to have basic image skills.

This lesson starts building those skills by exploring how computers display images.

This lesson’s goals

By the end of this page, you should:

  • Know what a pixel is.
  • Know how each pixel’s color is represented.
  • Know what a color channel is.
  • Know what anti-aliasing is.

Pixels

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.

Pixels

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.

Color codes

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.

Text and anti-aliasing

Photos have thousands of different colors, captured by a digital camera or a scanner. Text and drawings have fewer colors.

Text

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:

Anti-aliased text

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.

Summary

You learned:

  • That a pixel is a colored dot.
  • There are three color channels for each pixel.
  • That each pixel’s color is represented by an RGB code.
  • That anti-aliasing blends contrasting colors to make color transitions smoother.

What now?

Now let’s see how different file formats store color information.

Image formats

Where are we?

You learned how computers show images on a display. But how they’re stored in files is different. That’s what this lesson is about.

This lesson’s goals

By the end of this lesson, you should:

  • Know what an image format is.
  • Know the three main image formats used on the Web.
  • Know what transparency and translucency are.

What is an image format, anyway?

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.

The JPEG format

A raw image will contain many more colors than your eye can differentiate. Here are two objects:

Two colors

Figure 1. Two colors

They are different colors. One is (255, 159, 99). The other is (255, 159, 100). So one has slightly more blue. I can’t tell the difference. Can you?

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.

  1. Encoding programs, that use the JPEG algorithm to encode raw RGB. The encoded data is written to a file, which is smaller than a file with unencoded data would be.
  2. Decoding programs, that read JPEG encoded data from a file, and convert it back into RGB data that the computer shows on the display.

When your Web browser shows a JPEG image, 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. 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. Compare these two images.

Normal image
4.0K

Compressed too much
0.7K

Figure 2. Compressed too much

The good news is that the second file is tiny, even though the image itself ls larger. Too bad it’s junk.

JPEG is best for photos, which have thousands of colors. Throw some away, and your eye won’t notice.

The GIF format

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.

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

Animated GIF

Figure 3. Animated GIF

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

Frame 1

Frame 2

Frame 3

Frame 4

Figure 4. 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.

Cow
Cow

Figure 5. Transparent GIF

The PNG format

The portable network graphics (PNG) format was designed to replace GIF. PNG is lossless since it 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. That’s what GIF does. The cow in Figure 5 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:

Flamingo

Figure 6. PNG flamingo

Here’s a blue spot:

Blue spot

Figure 7. 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:

Flamingo Translucent circle

Figure 8. 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!

Searchlight

Figure 9. Searchlight

I wrote some JavaScript to move the searchlight over the text. The pixels in the searchlight have some translucency, so the text underneath always shows through.

Other formats

There are other graphics formats, but they don’t impact the Web as much as the Big Three. We won’t talk about them.

Which format should you use?

Use JPEG for photos, but don’t overcompress. Use PNG for everything else. There are lots of existing GIF images you can use on your sites. There’s no need to convert them to PNGs. Just use them as is.

Movies and animation

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 HTML code into your page to embed the movie in your site. YouTube gives you the code, so you can just copy-and-paste.

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.

Apple doesn’t support Flash on iPhones or iPads. These are popular devices. Some people think Flash is on the way out. Time will tell.

Summary

In this lesson, you learned about the Big Three formats: JPEG, GIF, and PNG. You learned about transparency and translucency.

What now?

Let’s talk about where you can get images for your pages.

Where images come from

Where are we?

You know what images are for (information, interface, 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?

This lesson’s goals

Images come from two sources. You make them, or someone else does. By the end of this lesson, you should:

  • Know how to find images other people have created.
  • Know about different image licenses.

Using other people’s images

There are millions of images you can use freely on your Web sites. But before you use an image, make sure you understand its license. A license is a legal document telling you what you can do with the image.

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.

Some licenses are more common than others. Here are some samples.

  • “Public domain” means that the image is free for any use, including commercial use.
  • An attribution license means that you can use the image, as long as you say where the image came from.
  • Free non-commercial use means that you can use the image for free on personal and non-profit sites. You may need to pay for commercial use.
  • Paid royalty-free non-exclusive license means that you pay once to use the image on a site, no matter how many people view your site. The “non-exclusive” part means that other people can buy a license for their sites as well.

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

Photos

You can get photos from many places. Here are a few.

BurningWell

BurningWell is a collection of public domain photos. The collection is not as large as some others, but there’s still a lot of stuff there, and all for free.

morgueFile

morgueFile is one of the better known free photo sites. The images can be used for commercial purposes. The photos are categorized and searchable.

US government photos

Links to various government sites. Most images are in the public domain, but not all.

123RF

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.

stockxpert

You can buy images to use on your Web site from $1 each. There’s some great stuff here.

Stock.XCHNG is part of this family of Web sites. Images can be used for free, with some restrictions. Check the license.

iStockphoto

Like stockxpert. Same parent company, in fact.

Exercise: Get some dog photos

Find a few dog photos we can use later in this lesson. Make sure they're public domain, or you can use them for free on personal sites.

Put the URLs of the images below. To find the URL of an image, right-click on it in Firefox, and select "View image info." The command may be different in other browsers.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Interface and structural

These are images for buttons, dividers, and so on. Look for images that come in sets, that is, a collection of buttons, dividers, and other elements that have the same look.

Open Source Web Design

Many complete site layouts, including image sets. The CoreDogs theme started with an OSWD design.

FullMoon Graphics

Some creative image sets.

Chibi Creations

Neat stuff, if you like chibies.

Google Directory

List of Web sets. Lots o’ stuff here.

Creating your own images

Digital camera

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.

Drawing software

Every Weber should be able to make simple drawings. We’ll talk about that on the next lesson.

Draw and scan

Robot dog
By zombiecatfire13

Zombiecatfire13 drew the robot dog, and said I could add it to CoreDogs. I scanned it in.

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, if you want. Give me the URL.

Summary

There are many sources for free and low-cost images. Make sure you follow license terms. When in doubt, ask.

What now?

Let’s cover some of the tools that should be in your image toolkit.

Your image toolkit

Where are we?

You need to have software to create and manipulate images. Let’s talk about some of the free tools that are available.

This lesson’s goals

By the end of this lesson, you should:

  • Know the types of tools you should add to your toolkit.
  • Have downloaded and installed a tool of each type.
  • Be able to complete some basic image tasks.

Image editors

Image editors let you mess with the pixels in images. You can resize, crop, and perform other operations on photos and images.

Paint.NET is a popular image editor for Windows. It’s free, and easy to use. It can handle common Web image tasks, cropping, resizing, recoloring, fixing artifacts in photos.

For the Mac, iPhoto can do some basic tasks. You can see a list of low-cost Mac image editors.

GIMP is another popular tool. It’s free, and runs on all the major operating systems. It’s more powerful than Paint.NET, but harder to use and harder to learn. I use GIMP for much of my image work.

We’ll use Paint.NET in CoreDogs. If you run Windows, you should download and install it.

Let’s look at some tasks you might do with these tools.

Cropping a photo

Often you want to use just part of a photo. Take this one, for example:

Awww

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.

Open the file in Paint.NET. Use the select tool. Choose part of the photo.

Selecting

Figure 2. Selecting

Now use the crop command.

Cropping

Figure 3. Cropping

You end up with a cropped image. W00f!

Cropped image

Figure 4. Cropped image

I can save it in a new file, and use it on a Web page.

Resizing a photo

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:

Resizing

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:

Squished image

Figure 6. Squished image

Not so good. Fortunately, Paint.NET will maintain the right ratio for me. I just leave “Maintain aspect ratio” checked.

Maintain aspect ratio

Figure 7. Maintain aspect ratio

I’ll make the image 50 pixels high, and leave the width alone. The software will compute that for me. I end up with:

Puppy icon

Figure 8. Puppy icon

Add text to a photo

Another common task is to add text to a photo. Check I Has A Hotdog! for examples.

Here’s the image I started with:

Renata and ball

Figure 9. 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.

I add the text into the new layer.

Adding text

Figure 10. Adding text

I got:

Meat taste

Figure 11. Meat taste

Since the text is in a separate layer, I still have the original image underneath. If I change my mind about what the text should say, I just change the text layer. I can delete the text layer, add a layer with other images, and so on.

Layers are important. Choose an image editor that has them.

To make the text look a little better, I added a slight raised effect. To do it, I added another layer underneath the text layer:

Shadow layer

Figure 12. Shadow layer

I copied the text layer, changed its color, moved it a little, and blurred it a little. Paint.NET stacks the layers on top of each other. This was the result:

Meat taste, raised text

Figure 13. Meat taste, raised text

The difference is subtle, but it’s there.

Exercise: Add a caption to a dog photo

Add a funny caption to one of your dog photos. Crop and resize the photo if you need to first.

If you need a dog photo, try morgueFile.com.

Paste a link to your image below. How? That’s coming up soon.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Drawing tools

So far, we’ve worked on photos and other pixel-based images. With these tools, you usually work with individual pixels:

Drawing tools are different. They make it easy to create drawings like this:

Ajax drawing

Figure 14. Drawing

This drawing combines a photo, screen shots, an icon, text, geometric shapes (the circles around the numbers), and curved lines with arrows.

Each element is a separate object. You can change each one separately. For example, I can grab one of the objects in Figure 14:

Selected a line

Figure 15. Selected a line

Then I can mess with that object, leaving everything else alone:

Changed object

Figure 16. Changed object

Moving all the pixels around to make the new line would be a pain. But I don’t have to. The drawing program makes it easy for me to reshape a line.

Drawing programs store images in many different formats. Web browsers can’t show most of them. So, when you have the drawing right, you make a bitmap copy, in a JPEG, GIF, or PNG. This is sometimes called “exporting” the image. I often use a screen capture program for this step, as we’ll see later.

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:

Dog happiness

Figure 17. Dog happiness

It’s a combination of a pixel object (the dog) and drawing objects (everything else). That’s common in Web work. You use pixel tools for photos and such, and drawing tools for lines and things.

First, I started with the dog. I got it from WP Clipart, a collection of public domain clip art.

Here’s the original drawing:

Original drawing

Figure 18. Original drawing

It’s a pixel object – a bunch o’ colored dots.

There are some artifacts around the dog. Artifacts are errors, like extra pixels or changes in pixel colors.

Artifacts

Figure 19. Artifacts

They usually result from problems when scanning an image from a book into a computer, or converting from one image format to another.

This is pixel work, so I used Paint.NET for this part of the task. The eraser tool can remove extra pixels around the head.

Removing artifacts

Figure 20. Removing artifacts

I zoomed in so I could work more easily. I set the radius of the erase to 5 pixels.

Once the artifacts were gone, I told Paint.NET to save the dog head as a PNG.

Then I started Draw, with a blank page. I told Draw to insert the dog head.

Next, I added some text:

Adding text

Figure 21. Adding text

I set the type face to Trebucet MS, the size to 10 pixels, and the color to dark gray.

Then I added a connector:

Adding a connector

Figure 22. Adding a connector

A connector is a line that connects two other objects. Notice the anchor points: the 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 use 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 23. Moving the text

Choose a drawing 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.

Dog happiness

Figure 17 (again). Dog happiness

Next I added the heart. I didn’t have to draw all of the lines separately. Draw includes a bunch of geometric objects: ovals, rectangles, talk balloons, triangles, smiley faces, jewels, jigsaw pieces, ... Each one can be sized, shaped, and colored independently.

When you choose a drawing tool, look for a tool that includes geometric objects.

Finally, I added a gradient to the heart:

Adding a gradient

Figure 24. Adding a gradient

You can see from the tabs at the top of Figure 24 that I could have filled the heart with a bitmap, hatching, and other things. Look for features like this in a drawing tool.

Now I’ve finished the drawing. W00f! Time to get it on a Web site.

Remember, there’s a problem. Browsers show images in JPEG, GIF, and PNG formats (and maybe others, but these are the Big Three that work in all modern browsers). But my drawing file is not in one of those formats. It has the extension .odg, used by OpenOffice Draw. Browsers don’t know how to show .odg files.

How do I get my drawing in one of the Big Three formats? There are various ways. I chose to do something simple…

Screen capture

This means saving a piece of your computer screen into a file. Often called a screen shot. A screen shot is a bitmap image, with the pixels that were on your screen.

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.

I use SnagIt for CoreDogs. It costs money, but is worth it if you do lots of screen captures.

Summary

On this page, you learned about image editors, image viewers, drawing programs, and screen capture programs. You learned how to do some basic tasks, like crop and resize images.

What now?

Now that you have some images, let’s see how we show them on a Web page.

Showing images on a page

Where are we?

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.

This lesson’s goals

By the end of this lesson, you should know how to use the <img> tag to show images.

The <img> tag

Use 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

Line 10 shows the <img> tag at work:

<img src="food_love_happiness.png">

Give the <img> tag the name of the file to show, in the src attribute. You can see this page in your browser.

Notice that your browser needs two files to show this page:

  1. The HTML file, with an extension .html.
  2. The image file, with an extension .png.

So image data are not stored in HTML files. Image data are stored in separate files. HTML files are always just plain text.

For now, we’ll keep all of our files in the same directory on the hard disk. So the directory for the page in Figure 1 might look like this:

Directory with HTML and image files

Figure 2. Directory with HTML and image files

When you upload the files to your server, upload both files, and keep them together.

It’s not always good practice to keep the files together. But we’ll deal with that later.

The alt attribute

src is the most important attribute of the <img> tag, but there are others. One is the alt attribute. You should add it to every image. It gives a text alternative to the tag when the image can’t be shown.

So the <img> tag about should really be something like:

<img src="food_love_happiness.png" alt="Food, exercise, and love = a happy dog">

There are two reasons you should use the alt tag.

First, 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.

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.

There’s a second reason you should use the alt tag: it helps search engines know what the image is about. People are more likely to find your page if you add alt attributes to your images.

Exercise: Show a drawing

Here a drawing of someone geeking out:

Geek

Download the image to your computer. Create an HTML page that shows the image. Use a relative URL for the image file.

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

Can't find the 'comment' module! Was it selected?

Summary

  • Use the <img> tag to show images.
  • Use the alt attribute to give a text alternative for each image.

What now?

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.

Styling boundaries - the box model

Where are we?

You know how computers represent images. You know how to find free images, and show them on a page. Let’s use CSS to add some styling to image boundaries.

This page’s goals

By the end of this lesson/page, you should:

  • Know what the box model is.
  • Be able to style image and text boundaries.

Boxes

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:

Paragraphs

Figure 1. Paragraphs

There is white space above, below, and to the left and right of each paragraph. Each <p> is in a box, a rectangle of space on the screen.

The text you’re reading now is in a box. You could draw a rectangle around the text, with “The” in the upper left, and “right.” in the lower right.

Browsers create boxes for <p>, <h1>, <h2>, <ul>, <ol>, and other tags. Including the <img> tag. Each one creates a box (a rectangular space) on the screen.

You control the box by using the CSS attributes border, margin, and padding.

Let’s start with the border.

The border attribute

You have lots of control over the border around an element.

Border style

Here’s a picture of me in the snow, with a solid border.

Solid border

Here’s the code:

.solid_border {
  border-style: solid;
}
...
<img class="solid_border" src="kieran_snow.jpg">

I created a class in the CSS (don’t forget the .), and set the border-style. I used the class in the HTML with the class attribute of the <img> tag.

Here’s a dashed border:

Dashed border

Here’s the code:

.solid_border {
  border-style: dashed;
}

The default border style is hidden, meaning no border.

There are more styles, like dotted and grooved. You can see the list at SitePoint.

There are four borders around the image: top, right, bottom, and left. border-style sets all four to be the same. You can give each one a different style. For example:

Mixed border

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, right, bottom, left. That’s in clockwise order from the top:

Border order

Figure 2. Border order

This ordering applies throughout CSS. For padding, margins, and other things we’ll see later.

Border width

You can set the width of borders like this:

Thick border

.thick_border {
  border-style: solid;
  border-width: 10px;
}

The width won’t show unless you set a style as well.

Border color

Set a border color using the usual color codes, the same ones used for fonts and everything else. For example:

Green border

.color_border {
  border-style: solid;
  border-width: 10px;
  border-color: #668014;  
}

Combining into one border style

Usually when I set colors, I specify color, style, and width, and want them the same for all sides. I put all the options in a single border style:

.color_border {
  border: solid 10px #668014;  
}

Margins and padding

We’re talking about boxes around elements. 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:

Dog matrix

Figure 4. Dog matrix

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:

Dog matrix with margin

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;
}

Dog matrix with padding

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:

Dog matrix with margin and padding

Figure 7. Dog matrix with margin and padding

The box model

Put border, margin, and padding together, and you have the box model.

The box model

Figure 8. The box model

The box model shows how border, margin, and padding combine. And the box model isn’t just for images.

Text, too

You can use the same properties with text. For example, let’s say you want to make a message stand out, like this:

Text standing out

Figure 9. 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.

Here’s a buttony thing made with the box model.

Box model example

Figure 10. Box model example

Thick gray borders on the bottom and right create a shadow. The thinner lines on the top and left add to the button effect. The color for the top and left is a slightly darker version of the background color.

Summary

Browsers use the box model to create rectangular areas on the screen. You can change the way the boxes look with border, margin, and padding.

What now?

You can make text wrap around an image. Let’s see how.

Floating images

Where are we?

You learned how to put an image on a page. You know how to put a border around it, with margins and padding. Time for more image fun.

This lesson’s goals

By the end of this lesson, you should know how to move an image to the left or right of a page, and have text wrap around it.

The goal

You’ve seen pages like this:

Renata

Blah blah blahity blah blah. Blah blah blahity blah blah. Blah blah blahity blah blah blah blah. Blah blah blahity blah blah.

Blah blah blahity blah blah. Blah blah blahity blah blah blah blah. Blah blah blahity blah blah blah blah. Blah blah blahity blah blah. Blah blah blahity blah blah. Blah blah blah blah blahity blah blah. Blah blah blahity blah blah.

Blah blah blahity blah blah. Blah blah blahity blah blah. Blah blah blah blah blahity blah blah. Blah blah blah blah blahity blah blah. Blah blah blahity blah blah.

Figure 1. Image floated left

The image is on the left of the page, and text wraps around it. There’s a small gap between the image and the text.

The image could be on the right:

Renata

Blah blah blahity blah blah. Blah blah blahity blah blah. Blah blah blahity blah blah blah blah. Blah blah blahity blah blah.

Blah blah blahity blah blah. Blah blah blahity blah blah blah blah. Blah blah blahity blah blah blah blah. Blah blah blahity blah blah. Blah blah blahity blah blah. Blah blah blah blah blahity blah blah. Blah blah blahity blah blah.

Blah blah blahity blah blah. Blah blah blahity blah blah. Blah blah blah blah blahity blah blah. Blah blah blah blah blahity blah blah. Blah blah blahity blah blah.

Figure 2. Image floated right

Let’s see how you do that.

Basic floating

Check out this code:

.left {
  float: left;
}
...
<p>
  <img src="renata.png" alt="Renata" class="left">
  Once upon a time, there was a dog named Renata. Renata
  was a happy hound. She liked to play, digging holes, 
  pulling ropes and chasing balls.
</p>

Figure 3. Floating left

There’s a paragraph from lines 5 to 10. The first thing inside the <p> is an <img> (line 6). It’s given a class of left. left is defined in the CSS, on lines 1 to 3.

float:left is applied to the image. Here’s what it looks like:

Floating left - result

Figure 4. Floating left – result

You can look at the page.

That’s all there is to it. The float property moved the image to the left.

Suppose I change the code to this:

.right {
  float: right;
}
...
<p>
  <img src="renata.png" alt="Renata" class="right">
  Once upon a time, there was a dog named Renata. Renata
  was a happy hound. She liked to play, digging holes, 
  pulling ropes and chasing balls.
</p>

Figure 5. Floating right

Line 2 says right instead of left. It looks like this:

Floating right - result

Figure 6. Floating right – result

You can try it.

Renata
Renata

Look at the code. You named the class left in Figure 3, and right in Figure 5. Did you have to do that?

Kieran
Kieran

No, I could have named the class anything. This would work the same:

.llama {
   float: left;
}
...
<img ... class="llama">

Or this:

.leaping_lemons {
   float: left;
}
...
<img ... class="leaping_lemons">

I named the classes left and right to describe what they do. It makes it easier to understand the HTML.

Adding whitespace

Here’s the image floated left:

Floating left - result

Figure 4 (again). Floating left – result

The text is right up against the image. It doesn’t look very good.

I can use the box model you just learned about to fix that. Suppose I changed the class to:

.left {
  float: left;
  margin-right: 10px;
  margin-bottom: 10px;
}

Figure 7. Making a gap

I’ve added a 10 pixel margin to the right of the image, and to the bottom of the image. Here’s what it looks like:

Making a gap - result

Figure 8. Making a gap – result

You can try the page.

Adding a border

As well as margin, the padding and border properties work on a floated image. Use them to make borders. Let’s say I wanted this:

With a border

Figure 9. With a border – result

There’s a small gap between the image and the border, then another gap between the border and the text.

Here’s the class:

.left {
  float: left;
  margin-right: 10px;
  margin-bottom: 10px;
  padding: 3px;
  border: 1px black solid;
}

Figure 10. With a border

You can try it.

The padding (line 5) adds the gap between the image and the border. The margin (lines 3 and 4) adds the gap between the border and the text.

Renata
Renata

A question.

Look at the gap between the bottom of the border and the text in Figure 10:

Vertical gap

Why is it so large?

Kieran
Kieran

The margin below the border drops just a little into the line of text starting with “the.” The browser won’t draw part of a line of text, so it drops down to the next line, leaving that big gap.

It’s hard to control this vertical gap precisely. It depends on the size of the font, whether the user has zoomed in, and other things.

Exercise: The dog party

Project Gutenberg is a collection of literary works that are not under copyright in the United States. Take a story from the collection, and float some illustrations left and right.

I used The Dogs’ Dinner Party, by an unknown author. Have a look at the original. You can use another story, if you want.

The story includes text and images. I only used a small part of the story. You can use more if you want. I shrank the images to this:

Writing invitations
Receiving an invitation

Figure 1. Smaller images

Float your images to the left and right, with a gap between images and text. Here is part of what I made:

Result

Figure 2. Result

Create your own story page, with the look you want. Make sure you float some images to the left, and others to the right.

Upload your work to your server. Enter the URL.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

  • You can float images left and right with the float property. Text wraps around the image.
  • Use the margin property to put space between the text and the image.
  • Use the border property to add a border to the image. Use padding to add space between the image and the border.

What now?

Let’s add captions to image.

Images and captions

Where are we?

You know how to put images on a page. And you know about the box model. Now let’s put them together, so captions float around with their images.

This lesson’s goals

You’ll learn that:

  • Captions can be above or below images.
  • An image and a caption can be wrapped in a <div>, making a single block.
  • An image-caption block can be floated left and right.
  • You can add borders to image-caption blocks.

Caption options (say that five times fast)

Some images on Web sites have captions. Here’s an example:

Bulldog

Bulldog

There’s an <img> tag and some text. But we want them to stay together. That’s what this lesson is about.

Let’s talk about some formatting options:

  • Caption position
  • Image block position
  • Borders.

Caption position

This one’s easy. Is the caption above or below the image?

Like this:

Bulldog

Bulldog

Or like this:

Bulldog

Bulldog

Here’s the code for the latter:

<p><img src="bulldog.jpg" alt="Bulldog"></p>
<p>Bulldog</p>

Image block position

Wrap the image and caption in a block, and you can position them in the page. For example, this image and caption are kept together on the left of the page:

Bulldog
Bulldog

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

The image and caption float together, as a single unit.

Here’s the code.

.image_caption_left {
  float:left;
  text-align:center;
  margin-right:10px;
}
...
<div class="image_caption_left">
<img src="/content_media/lessons/clientcore/web_page_with_images/bulldog.jpg" alt="Bulldog"><br>
Bulldog
</div>

<p>Blah blah blahity blah. Blahity blah blah. Blah! 
Blah blah blahity blah. Blahity blah blah. Blah! 
Blah blah blahity blah. Blahity blah blah. Blah! 
Blah blah blahity blah. Blahity blah blah. Blah! </p>

A <div> wraps the image and caption (lines 7 to 10). It keeps the image and caption together. When we move the <div> around, we move the image and caption as a single unit.

float: left; (line 2) positions the block to the left of the content. margin-right:10px; (line 4) leaves a small gap between the block and the blah blah blah.

Now let’s look inside the block. A <br> (end of line 8) puts the image and caption on different lines. text-align:center; (line 3) centers the image and caption within the block. text-align applies to the contents of the block, not the block itself.

Changing line 9 to this:

<em>Bulldog</em>

makes it easier for the user to see that the caption is not part of the regular text. Here’s what it looks like:

Bulldog
Bulldog

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Of course, you can float to the right as well:

Bulldog
Bulldog

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Here’s the code.

.image_caption_right {
  float:right;
  text-align:center;
  margin-left:10px;
}
...
<div class="image_caption_right">
<img src="/content_media/lessons/clientcore/web_page_with_images/bulldog.jpg" alt="Bulldog"><br>
Bulldog
</div>

<p>Blah blah blahity blah. Blahity blah blah. Blah! 
Blah blah blahity blah. Blahity blah blah. Blah! 
Blah blah blahity blah. Blahity blah blah. Blah! 
Blah blah blahity blah. Blahity blah blah. Blah! </p>

The easiest thing of all is to center the image:

Bulldog

Bulldog

Here’s the code.

.center {
  text-align:center;
}
...
<p class="center"><img src="/content_media/lessons/clientcore/web_page_with_images/bulldog.jpg" alt="Bulldog"></p>
<p class="center"><em>Bulldog</em>

Borders

Let’s add a border to the image-caption block.

Bulldog
Bulldog

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Here’s the code.

.image_caption_left {
  float:left;
  text-align:center;
  margin-right:10px;
  padding:5px;
  border:1px black dotted;
}
...
<div class="image_caption_left">
<img src="/content_media/lessons/clientcore/web_page_with_images/bulldog.jpg" alt="Bulldog"><br>
<em>Bulldog</em>
</div>

<p>Blah blah blahity blah. Blahity blah blah. Blah! 
Blah blah blahity blah. Blahity blah blah. Blah! 
Blah blah blahity blah. Blahity blah blah. Blah! 
Blah blah blahity blah. Blahity blah blah. Blah! </p>

Lines 5 and 6 are new. Line 5:

padding:5px;

adds whitespace between the image and caption, and the border. Line 6:

border:1px black dotted;

adds the border. Of course, you can change the thickness, color, and style of the border.

Summary

  • Captions can be above or below images.
  • An image and a caption can be wrapped in a <div>, making a single block.
  • An image-caption block can be floated left and right.
  • You can add borders to image-caption blocks.

What now?

A cool thing you can do with Web pages is to add background images. Let’s take a look.

Background images

Where are we?

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.

This lesson’s goals

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 lesson, you should:

  • Be able to add a tiled background.
  • Be able to add a single image background.

A tiled background

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, from the Zen Garden. 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:

Background tile

Figure 1. 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 2. Using the tile

Figure 2 is not a screen shot. It’s made by some HTML and CSS I typed into this page. Here’s roughly what I did to create Figure 2.

...
.tiled {
  font-size: 20px;
  color: white;
  padding: 20px;
  background-image: url('tile.gif');
}
...
<div class="tiled">
  <p>Hi there!</p>
  <p>This is a tiled background. 
  Notice how the edges of the tile are seamless?</p>
  <p>There are a bazillion seamless tiles you can use
  for free, or you can make your own.</p>
  <p>We now return you to your regular background.</p>
</div>

Figure 3. Making Figure 2

There are two new things here.

<div>

There’s a new tag: <div>. <div> groups other tags together. Then, what you do to the <div> affects the entire group.

<div> is used to make a container on the page. Have another look at Figure 2. Figure 2 is a chunk of this page that I wanted to be different from the rest. With a different font, and with a background.

But how do I tell the browser that I just want to treat that one part of the page differently? That’s what <div> is for. It makes a container. By styling the container, I style everything in it.

In fact, most HTML tags create containers. Consider this code:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Container Samples</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style type="text/css">
      .dog {
        /* Pale blue */
        background-color: #99FFF9;
        font-size: 22px;
      }
      .cat {
        /* Pale green */
        background-color: #B3FF84;
        font-size: 11px;
      }
    </style>
  </head>
  <body>
    <p class="dog">
      I am the <strong>first</strong> container.<br>
      Yes. I am.
    </p>
    <p>I'm a container, too. I am the second container.</p>
    <p class="cat">
      I think I am the third container.
    </p>
  </body>
</html>

Figure 4. <p>s are containers

You can try it. This is what you’ll see:

Rendered containers

Figure 5. Rendered containers

I wanted every character in the text “I am the first container” to be in a large font. The easiest way to do it? Look for a container that holds the text. There was one already there – the <p> starting on line 20. So I gave it a class, and made a rule for the class in the CSS.

Use <div> when there isn’t already a container for the content you want to mess with. <div> by itself doesn’t actually show anything on the screen. It’s just for creating containers.

background-image

Here’s Figure 3 again:

...
.tiled {
  font-size: 20px;
  color: white;
  padding: 20px;
  background-image: url('tile.gif');
}
...
<div class="tiled">
  <p>Hi there!</p>
  <p>This is a tiled background. 
  Notice how the edges of the tile are seamless?</p>
  <p>There are a bazillion seamless tiles you can use
  for free, or you can make your own.</p>
  <p>We now return you to your regular background.</p>
</div>

Figure 3 (again). Making Figure 2

The first new thing in it was the <div> tag. The second new thing is background-image:

background-image: url('tile.gif');

You tell the browser the name of the file you want to use as a background. Don’t forget the url(). For now, let’s put the tile file in the same directory as everything else, just to keep things simple.

By default, the browser repeats background images across and down the container, filling up the background:

Repeating tiles

Figure 6. Repeating tiles

That’s why the tiles have to be specially designed to fit together. Most images don’t work as tiles. Here’s a (resized) photo of my desk:

Desk

Figure 7. My desk

I cropped and resized part of it, and created the following:

Desk tile

Figure 8. Desk tile

Let’s try it.

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 9. Using the desk tile

Uh oh. Not so good. When it’s repeated, the edges don’t fit together.

The lesson: use images specially designed to be seamless tiles.

Some tiles are designed to be repeated in one direction, but not the other. Here’s another tile from GRSites.com:

Another tile

Figure 10. Another tile

The tile is wide, to stretch across a large container.

We want the image to tile like this:

Repeat vertically

Figure 11. Repeat vertically

We only want the tile to repeat vertically. We don’t want it to repeat horizontally, otherwise the red line on the left of the “paper” would appear more than once.

Check this out:

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 12. Using the tile

Here’s the CSS:

.notepaper {
  font-size: 16px;
  color: black;
  padding: 20px 20px 20px 100px;
  background-image: url('paper_background.gif');
  background-repeat: repeat-y;
}

Figure 13. CSS rule for notepaper background

By default, browsers repeat background tiles in both directions. Line 6 overrides that. It tells the browser to repeat vertically only.

What happens when you don’t do it right? I’ve taken another paper background image from GRSites.com. Please have a look. I added a border so you can see the edges of the image.

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:

Cropped tile

Figure 14. Cropped tile

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 15. Using the cropped tile

Remember, the browser’s default action is to repeat background images in both directions. 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 16. 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 17. Using the cropped tile with background-repeat:repeat-y;

Ahhhh… Much better.

Using one large image

You can use one large image to set a mood, as seen on this page. This might be a page on a landscaping site, or one about nature vacations.

First, I created the image with the fade effect:

Background image

Figure 18. Background image

I won’t explain how I made the image, since it’s not a core concept. There’s an article if you’re interested.

Now that I have the image, I want to put it in the upper right 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>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 19. Page with a background image

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 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;

Summary

On this page, you learned how to add background images to a page. You learned how to add tiles, and a single large image. You learned how to use background-repeat:repeat-y; for tiles that are designed to repeat vertically only.

What now?

Let’s talk a bit more about color. How do you select image colors, font colors, etc., that look good together?

eMe: Images

Where are we?

You know how to show images, how to create them, how to show them on a page, and how to style them (with the box model).

Let’s talk about your eMe. Remember, that’s the site you’ll use to promote your personal brand to employers and/or clients.

What is your brand?

You need to know what your eMe will say about you. We talked a little about this before.

If you’re like many people, you’re not sure about this. You might even be uncomfortable about calling yourself a “brand.”

Renata
Renata

I was thinking that.

Kieran
Kieran

What?

Renata
Renata

I’m not a…, well, a washing detergent.

Kieran
Kieran

Let me ask you this. What is a brand?

Renata
Renata

Ah, it’s…, um, a thing for advertising. Isn’t it?

Kieran
Kieran

Not really. It’s a set of beliefs that people attach to something.

Advertisers care about this. When you think “Google,” the Google people want certain beliefs to jump into your mind. Same with “Burger King” (yum!), “Apple,” and “Pontiac.”

Renata
Renata

I’m not like those things!

Kieran
Kieran

You are in one sense. When an employer or client thinks about you, you want certain beliefs to pop into their heads. Is that right?

Renata
Renata

No!

Kieran
Kieran

But beliefs will pop into their heads. People are just wired that way.

Kieran
Kieran

Well, I guess. That’s what I learned in Psych 101.

Kieran
Kieran

So it’s a question of what beliefs. How about “resentful,” “dull,” and “angry?”

Renata
Renata

I’m none of those things!

Kieran
Kieran

I know. But when someone doesn’t know you, beliefs can come from anywhere.

Use your eMe to say positive things about yourself. Things that are true. Simply point out the good things about you. That you are playful, for example.

That’s what personal branding is about. Pick some attributes of yourself that you want to highlight. Then create consistent messages about those attributes.

People in the business call it “personal branding.” You can call it something else if you like.

One thing. Never lie on an eMe. Never stretch the truth. Advertisers do it all the time. They encourage consumers to form inaccurate beliefs, without telling direct lies. Well, not usually.

This is where branding gets a bad name. But just because advertisers sometimes mislead, doesn’t mean that you should. You can create an eMe with honesty and integrity.

Feel any better about it?

Renata
Renata

Yes, I suppose. But promoting myself still feels kind of weird.

Kieran
Kieran

I get that. Many people are taught not to be too proud. But talk about yourself honestly, and you’ll be OK.

By the way, do you know how you want to promote yourself yet?

Renata
Renata

Not really.

Kieran
Kieran

Keep thinking about it.

Renata
Renata

OK.

Your brand will probably include things like “professional,” “easy to work with,” and “fun” (maybe in there, maybe not). You’ll need some photos of yourself. Here are some you should have.

  • You in professional dress. Dress collar (dogs), suit (humans). A tie if you’re a male human. I don’t understand ties. But humans seem to think they mean something. Odd.
  • You in business casual. Smart, colorful collar (dogs). Humans have different rules. Wearing just a collar is not enough for them. Do some Googling about business casual.
  • You with a team, if teaming is an aspect of your brand. Find some photos of yourself working with others.
  • You having fun. Running with the pack, chewing on a rope, chasing squirrels, whatever you’re into. Make sure the photos are attractive and make sense to someone not into your things. For example, don’t include a photo of you with a shredded squirrel corpse. Unless you want a hunting job.

Collecting your photos

Make a directory on your server. Upload photo files there. You might not use all of them immediately. But they’ll come in handy one day.

Colors and color schemes

Where are we?

You need to create the right look and feel for your Web site. You learned earlier that look and feel includes:

  • Page layout
  • Colors
  • Images
  • Typography
  • Effects

Let’s talk about color in this lesson. Both text and images have color. Text color is set with CSS. Image color is part of the images themselves. Choosing a set of colors that work well together is hard for, er, artistically challenged people like me.

This lesson’s goals

By the end of this lesson, you should:

  • Know what a color scheme is.
  • Know how to describe individual colors.
  • Know about different types of color schemes, like monochrome and analogous.
  • Be able to decide what you want from a color scheme.
  • Be able to extract a color scheme from a photograph.

The goal: A color scheme

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:

Color schemes

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.

  • Usable – can the visitor read the content comfortably?
  • Aesthetics – do the colors invoke the right mood?

Colors in CSS

CSS rules set colors for text. Colors in CSS are usually represented as three numbers: the amount of red, green, and blue (RGB) 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;

“Hexadecimal” is just another way of writing numbers. 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.

The rest of the lesson

This lesson 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:

  • Individual colors
  • Relationships between colors

Describing individual colors

When people work with color, they want to say things like “make that blue brighter,” or “let’s try a paler orange.” That’s the way we’re used to talking about color.

It’s hard to do those things with RGB codes. Here’s an orange, and its RGB code:

Orange

Figure 2. Orange

How would you change the RGB code to make it paler? I’ll wait.

Oooo oooo ooooooo, ooo oooo ooo ooooooo oo,
Oooo oooo ooooooo, ooo ooo ooo ooo.

Figured it out? No? Don’t worry, I can’t figure it out either. People just can’t work with RGB codes. It’s too hard to figure out how much red, green, and blue to add (or subtract) to make a color paler.

RGB is precise, and it works for computers, but not for people. Is there something we can use instead of RGB, that’s also precise, and that people can use?

HSV works. It stands for Hue, Saturation, and Value. There’s a number for each one. So there are three numbers, just like RGB, but they mean different things.

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:

Color wheel

Figure 3. 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.

Primary hues

Figure 4. Primary hues

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

Mixing hues

Figure 5. 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:

Secondary hue

Figure 6. Secondary hue

So the first part of an HSV color is the hue.

You may say to yourself, “Self, there are lots of colors missing. Where’s the dark green of the leaves on my favorite tree?” Your self is right. Give he/she/it a cookie.

This is where the other two parts of HSV – saturation and value – come in. Saturation is the intensity of a color. Value is how bright the color is.

I had a hard time figuring out what saturation and value actually meant until I saw a chart like this one.

Saturation and value

Figure 7. Saturation and value

This shows the pure red hue with different amounts of saturation and value. The color that is the most red (in the upper right) has high saturation and value. A pastel red (that is, pink) has low saturation, but high value – low intensity, high brightness. Dark red (looks like brown) has medium intensity and value.

If you have a good natural sense of color, your probably understand what saturation and value are by now. If you grok (“get it”), you can skip down a few paragraphs to the tints and shades section.

But I have to admit, I don’t have a natural sense of color. I needed to do some more thinking before I figured out HSV.

Here’s the way I think of it. The column on the left gives you a base amount of brightness to work with. For the grays in the left column of Figure 7, the amount of red, green, and blue is all the same. That’s what makes gray. The more of each color there is, the brighter the gray gets.

Grays

Figure 8. Grays

You get to white when red, green, and blue reach 255, their maximum value.

Renata
Renata

Is there anything special about those numbers, 215, 175, 135, and so on?

Kieran
Kieran

No. I wrote a program to create the display in Figure 7. The program just happened to end up with those numbers, when it had made an image I liked.

Nothing special about the numbers, except for 255. That’s the maximum for a color. The minimum is 0. rgb(0, 0, 0) is black – no colors at all.

Let’s pick a row from Figure 7:

Value and hue constant

Figure 9. Value and hue constant

The value is all the same in the row. The colors are equally bright. As we increase the red saturation, the ratio of the amount of red to the amount of green and blue gets bigger and bigger. But the colors remain dull, because they all have the same brightness.

Tints and shades

The colors on Figure 7 are all tints and shades of red. You get a tint of a color if you add white to it. You get a shade of a color if you add black to it.

Tint and shade

Figure 10. Tint and shade

The bottom line

For me, color is hard to think about. Maybe my brain is just not wired that way. But I know people who have no trouble with it.

What to do when you’re talking to another person about color on a Web site? Have some charts like Figure 7 handy. Then you can say, “These are all reds, but different kinds of reds.”

More on this later.

Let me show why HSV is so handy. I wanted a buttony thing with a green background, and darker edges. This video shows how HSV and Paint.NET helped me do that.

Describing the relationships between colors

We can describe a color by talking about its hue (base color), saturation (intensity), and value (brightness). But that’s only half the story.

A color scheme is not just one color. It’s a bunch of colors that work together to create an overall effect. We need a way to talk about collections of colors.

We’ll describe color schemes by how they use the color wheel. You saw a color wheel earlier.

Color wheel

Figure 3 (again). Color wheel

The wheel shows different hues.

You can make color schemes based on the color wheel. Let’s talk about different types of color schemes.

Monochrome with accent color

A monochrome scheme is a set of tints and shades of one hue. Recall that a tint is a hue (like red) mixed with white. A shade is a hue mixed with black.

Monochrome schemes don’t have to be black-and-white (although they can be). Here is a monochrome scheme from Color Scheme Designer:

Color Scheme Designer

Figure 11. Monochrome scheme

The base color is in the middle. Tints and shades surround it.

Usually a monochrome color scheme by itself is not enough for the Web. You’ll need an accent hue, used to highlight things you want to draw people’s attention to. Like a special offer. Use accents sparingly.

Here’s a black-and-white monochrome scheme, from Khoi Vinh’s Web site:

Monochrome site

Figure 12. Monochrome site

What a handsome fellow! Reminds me of someone.

When you put the mouse cursor on an article name, you see an accent color:

Accent

Figure 13. Accent

If you need more than one accent color, consider making them tints and shades of the same hue. So if the accent is green, have a few different greens you can use as accents.

Here is a monochrome design based on blue, with an orange accent:

Blue monochrome

Figure 14. Blue monochrome

I cheated a bit on this one. The actual design has some fish and things, to punch it up a bit. You’ll see that later.

Since black, white, and gray are neutral, any hue will stand out, and can be an accent color. But when a monochrome scheme uses a different base color, like the blue in Figure 14, you have to be more careful. Try using an accent hue that’s directly opposite on the color wheel:

Accent color for blue

Figure 15. Accent color for blue

This is exactly what’s happening in Figure 14.

Two hues are complementary if they are directly opposite each other on the color wheel. They have high color contrast.

If you use a bright, low saturation color for a background, most dark colors can be accents, even if they are not complementary. Here’s an example from Winnie Lim’s site:

Accent color for bright, low saturation background

Figure 16. Accent color for bright, low saturation background

Most of the page uses shades and tints of brown. The dark red makes a nice accent. It’s not opposite brown on the color wheel, but it looks OK because the background is pastel (bright, with low saturation).

Notice the picture of the dogs. It uses different colors entirely, and adds visual punch to the page. This is an accent object, something that stands out.

Here’s another example of fishy accent objects. The page Figure 14 is based on actually looks like this:

Accent objects

Figure 17. Accent objects

The yellow-orange color of the accent objects is complementary (that is, opposite on the color wheel) to the basic blue of the site. The fish automatically draw the viewer’s attention.

Complementary color schemes

We just saw a monochrome scheme with an accent color. The accent color might be the complement of the base color, that is, opposite on the color wheel.

Suppose you use the opposite color not just to accent the occasional element. You use it as one of the main colors of the site. Then you get a complementary color scheme.

Complementary schemes create a high-energy, vibrant look. They feel different from monochrome schemes, which seem more plain.

Some reds and greens are complementary:

Red and green

Figure 18. Red and green

Here’s a site that uses them:

Complementary scheme in action

Figure 19. Complementary scheme in action

This page uses tints and shades of green and red.

Analogous with an accent hue

Analogous schemes use colors that are close to each other on the color wheel. They are more peaceful, less jarring than complementary schemes.

Here’s an example from Arcion, a company that, among other things, sells complete Web site templates.

Analogous scheme

Figure 20. Analogous scheme

As before, you can use a color from the opposite side of the color wheel as an accent hue. Tints and shades of red might work well.

Other schemes

There are triadic, rectangle, square, and other schemes. The names are based on how the schemes use the color wheel.

We’ll just stick with the three we have:

  • Monochrome
  • Complementary
  • Analogous

TigerColor’s color harmony page explores other types of schemes.

Creating a GECS

As you can see, color is a complicated topic. So what do you actually do in a real Web project?

This section explains how you can make a GECS. GECS stands for Good Enough Color Scheme.

The general approach is to:

  • Understand what you want.
  • Use something that somebody else has created.

Of course, don’t go stealing things willy nilly. Use color schemes and designs that you have permission to use. Use things that are free, or buy the right to use them.

Let’s start with the first step.

Know what you want

Often, you aren’t entirely free to choose colors. Your employer might already have some standard colors. Look at the IBM site; IBM isn’t called Big Blue for nothing.

If there isn’t a standard color set, there may be a logo that you must use. There might also be product photos or other graphic objects that you must include.

If you have to match a photo’s colors, there are tools that can help. They will analyze a photo, and create a color scheme based on it. You can use the scheme directly, or modify it to meet your needs.

DogOne tool is Whats its color. You can upload a photo, or enter the URL of one. Give it a try. Pick a photo, upload it, and see what colors are in it. Download the photo on the right if you don’t have one of your own handy.

If you have standard colors, a color logo, product photos, etc., these colors are the beginning of your color scheme.

Now list some words to describe the mood you want from the site. “Serene” and “peaceful” suggest blues and greens in a analogous scheme. “Lively” and “fun” suggest something else.

Pick a few colors (including accent colors). Play with tints and shades. You won’t stay with them, necessarily. They’re a starting point.

There are many fun tools to play with. Sharebrain has a nice list of color tools. Check it out.

The goal here is not to settle on a color scheme, but to understand what you want. If you don’t know what you’re looking for, how are you going to choose the right thing?

So look at the logos, think about the site’s mood, and play around for a while.

Look at color schemes

Now take a look at some color schemes that other people have created. There are three options here:

  • Look at color schemes only
  • Look at complete designs
  • Sample existing pages and images

There are many color scheme galleries. I mentioned Colors on the Web earlier. Color Schemer is another one.

Another good option is to look at complete designs, that include colors and graphics. One of my favorite sources is Open Source Web Design. Here are some of their offerings:

OSWD designs

Figure 21. OSWD designs

It helps to know roughly what you’re looking for before looking at a design gallery.

A third choice is to base your colors on something that already exists, either a Web site or an image. There are tools that will help you figure out the colors being used. ColorZilla is an add-on for FireFox. When you install it, it adds an eyedropper to the Firefox status bar:

ColorZilla

Figure 22. ColorZilla

Click it to sample any color in the browser window.

The real fun starts when you right-click, and start the color analyzer.

Starting the color analyzer

Figure 23. Starting the color analyzer

ColorZilla will analyze the page, and give you the color scheme:

The color analyzer in action

Figure 24. The color analyzer in action

Exercise: Get a page's color scheme

Find a Web page you like. Use ColorZilla to get the colors on the page (you’ll need to install ColorZilla in Firefox).

Create a Web page like this one, showing some of the main colors on the page. Show maybe five or six colors, or however many are needed to show the main colors on the page.

I took a screen shot of part of the page. If you don’t have a screen capture tool on your Windows computer yet, try PicPick and Gadwin PrintScreen. Mac users will have to find something else.

You can look at the HTML of my solution to see how to write your own page.

Upload your solution to your Web server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Choose a scheme

You have thought about what you want, played around with some color schemes, and looked at some alternatives. Choose the scheme you will use. If you’re creating a site for someone else, ask them to approve your choice before you invest too much time in graphics and such.

Summary

  • You want to choose a color scheme, a set of colors that work together.
  • Individual colors have a hue (basic color), saturation (intensity), and value (brightness).
  • A tint is a color with white added to it. A shade is a color with black added to it.
  • Types of color schemes include monochrome with an accent color, complementary, and analogous with an accent color.
  • You need to understand what you want before choosing a color scheme.
  • You can download complete designs, that include colors and graphics.
  • You can generate a color scheme from a photo.

What now?

Time to make a color scheme for your eMe site.

Changing images - jQuery and the if statement

Where are we?

You know how to show an image on an HTML page. But the image doesn’t have to just sit there. You can hide images, show them, change their size, and other stuff.

This page’s goals

By the end of this page, you should:

  • Be able to show and hide images based on events.
  • Understand how a basic if statement works.

Review: Showing and hiding text

In the previous chapter (A Web page that interacts), you learned how to use JavaScript to show and hide text. Let’s look at an example to refresh your memory.

Let’s create a Web page with a dog riddle. The question is shown to start with:

Dog joke start

Figure 1. Dog joke start

Click the text that says “Click to show/hide the answer,” and you see:

Dog joke answer

Figure 2. Dog joke answer

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>Dog Joke</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() {
        $("#answer").hide();
        $("#toggle_answer").click(function() {
          $("#answer").toggle('slow');
        });
      });
    </script>
  </head>
  <body>
    <h1>A Dog Joke</h1>
    <p>What do you get if you cross a Red Setter with a Pointer?</p>
    <p id="toggle_answer">Click to show/hide the answer</p>
    <blockquote id="answer">A Pointsetter, the Christmas dog.</blockquote>
  </body>
</html>

Figure 3. Dog joke code

Remember that an event is something that happens. The ready() event happens when a page has been loaded. Lines 9 to 12 are run when the page has been loaded, but just before it is shown to the user.

Line 9 hides the answer to the riddle. Lines 10 to 12 set up the the click() event for the thing with the id of toggle_answer (don’t forget the # to tell the browser to look at the id attribute). When toggle_answer is clicked, toggle the visibility of the thing with the id of answer.

Showing and hiding an image

You can do the same thing with an image. Let’s create a page with a button on it that shows and hides a picture of a puppy. It will start like this:

Show puppy start

Figure 4. Show puppy start

Click the button, and you see:

Show puppy start

Figure 5. Show puppy end

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>Cute Puppy</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() {
        $("#puppy_container").hide();
        $("#show_hide_puppy").click(function() {
          $("#puppy_container").toggle('slow');
        });
      });
    </script>
  </head>
  <body>
    <h1>A Cute Puppy</h1>
    <p><button id="show_hide_puppy" type="button">Show/hide puppy</button></p>
    <p id="puppy_container"><img src="renata_young.jpg" alt="Cute puppy"></p>
  </body>
</html>

Figure 6. Show puppy code

The JavaScript is the same as before. The only thing that’s changed is the object that’s being shown and hidden. It’s puppy_container.

Note how I named it. puppy_container is a <p> tag that contains the <img> tag that shows the image.

Exercise: Show and hide a drawing

Here’s a drawing:

Yummie

Create an HTML page with a button that shows and hides the drawing.

Upload to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Changing the button caption

For our next trick, let’s change the button’s caption in the puppy show program. The button says “Show/hide puppy.” Let’s make it say “Show puppy” or “Hide puppy,” depending on whether the photo is showing or not.

The page will start like this:

Show puppy, simpler button

Figure 7. Show puppy, simpler button

Press the button, and get:

Nice puppy!

Figure 8. Nice puppy!

You can try the page.

Notice that the text on the button has changed. So, both the image and the caption switch back and forth between two states. When the image is not showing, the caption says “Show puppy.” When the image is showing, the button says “Hide puppy.” When the user clicks the button, both the image and the button change.

To show and hide an image, there’s the handy toggle() function. Toggle does some work for us. If the thing being toggled is showing, toggle() hides it, and vice versa.

There is no built-in function for toggling button captions. We have to handle the change ourselves.

First, I’ll work out the logic. I’ll write pseudocode.

When the button is clicked:
  Get the button caption
  If the caption is "Show puppy"
    Make the caption say "Hide puppy"
  If the caption is "Hide puppy"
    Make the caption say "Show puppy"
  Toggle the image

Figure 9. Pseudocode for the button click

Click the button, then click again, then click again, then click again, and the button’s caption will go back and forth between “Show puppy” and “Hide puppy.”

Let’s write it in JavaScript.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Cute Puppy</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() {
        $("#puppy_container").hide();
        $("#show_hide_puppy").click(function() {
          var button_caption = $("#show_hide_puppy").text();
          if ( button_caption == "Show puppy") {
            $("#show_hide_puppy").text("Hide puppy");
          }
          else {
            $("#show_hide_puppy").text("Show puppy");
          }
          $("#puppy_container").toggle('slow');
        });
      });
    </script>
  </head>
  <body>
    <h1>A Cute Puppy</h1>
    <p><button id="show_hide_puppy" type="button">Show puppy</button></p>
    <p id="puppy_container"><img src="renata_young.jpg" alt="Cute puppy"></p>
  </body>
</html>

Figure 10. Toggling the button’s caption

Getting text

Line 11 is:

var button_caption = $("#show_hide_puppy").text();

This will get the current value of the button caption, and put it into the variable button_caption. Then we can test it.

This is a different use of the text() function. Earlier, we used text() to set the text in something, like this:

$("#best_color").text("Green")

This put the text Green into the thing with the id best_color.

You can also use text() to get the text in something. That’s what happening in line 11. Leave the parenthesis (that is, the () ) empty, and jQuery will return the text that’s already in the object.

Several jQuery functions are like this. We’ll see more of them later.

Testing stuff

Line 12 introduces the if statement. The if statement lets browsers make decisions, doing different things depending on the circumstances.

The if statement only has two possibilities. It does one thing, or the other, and that’s it. Other statements let you have more than two options, but that’s for a future lesson.

The if statement looks like this:

if ( test ) {
  stuff to do if test is true
}
else {
  stuff to do if test is false
}

Figure 11. Iffy if, the ifster

The test is usually a comparison of some sort. The == in line 12 means “is equal to.” It’s true when the things on either side of the == are the same. Otherwise, it’s false.

Don’t confuse = and ==. They’re different. = means “put the thing on the right into the variable on the left.” == means “compare the things on the right and left.”

Back to the example.

var button_caption = $("#show_hide_puppy").text();
if ( button_caption == "Show puppy") {
  $("#show_hide_puppy").text("Hide puppy");
}
else {
  $("#show_hide_puppy").text("Show puppy");
}

(Part of) Figure 10 (again). Toggling the button’s caption

So line 12 says,

Is the variable button_caption equal to Show puppy?

If it is, the browser runs line 13, setting the button’s text to Hide puppy. If it isn’t, the browser runs line 16, setting the button’s text to Show puppy.

Exercise: Caption update

You wrote a page to show and hide a pretzel. Update it so that it changes the button’s caption appropriately.

Upload your file to the server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Now try this one.

Exercise: Two photos

Find two photos of animals. Create a Web page with two buttons and the two photos. One button shows and hides one of the images. The other button shows and hides the other.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

In this lesson, you learned how to show and hide an image in response to an event. You saw your first example of the if statement.

What now?

With just what you know now, you can make a slide show page. Let’s do it.

eMe: Making a slideshow

Where are we?

You learned how to show and hide an image. You saw the if statement in action. Now let’s make a simple slide show for your eMe.

What about? Pick something from your interesting stuff list.

This page’s goals

By the end of this page, you should:

  • Know how to control a sequence of events.
  • Know how to restart an event sequence when it gets to the end.

Slide show behavior

Let’s make sure we know what we want from the slide show.

Please try the page. Click on the arrow a few times. Notice that there are four photos. The show cycles back to the first one when it’s done.

The page is showing one image, cycling it as the user clicks.

Image cycle

Figure 1. Image cycle

We’ll actually use only one <img> tag. By changing its src attribute, we’ll change which photo the <img> tag is showing.

Suppose we gave each photo a number. This is what would be happening.

Numbered image cycle

Figure 2. Numbered image cycle

The slide number starts at 1. On each click, it goes up by one. When it gets to 4, a click sends it back to one. Each event is a step in the cycle. Click – 1 – click – 2 – click – 3 – click – 4 – click – 1 – click – 2 – ...

Let’s move closer to the actual code. Suppose we name the image files slide1.jpg, slide2.jpg, slide3.jpg, and slide4.jpg. The name of the image for the current slide would be:

slide + the slide number + .jpg

If we could put that into the src attribute of the <img> tag, it would show the current slide.

Closer to code

Figure 3. Closer to code

Here’s some pseudocode for the click() event:

Increase the slide number by one.
The new slide name is (slide + slide number + .jpg).
Set the <img> tag's src to the slide name.

Wait a minute. I forgot something. There is no slide 5. Hmm. How about this?

Increase the slide number by one.
If the slide number is more than 4, make it 1.
The new slide name is (slide + slide number + .jpg).
Set the <img> tag's src to the slide name.

That’s better.

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>Slide Show</title>
    <style type="text/css">
      #forward {
        cursor: pointer;
      }
    </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() {
        var slide_number = 1;
        $("#slide").attr("src", "slide" + slide_number + ".jpg");
        $("#forward").click(function() {
          slide_number ++;
          if ( slide_number > 4 ) {
            slide_number = 1;
          }
          $("#slide").attr("src", "slide" + slide_number + ".jpg");
        });
      });
    </script>
  </head>
  <body>
    <h1>Slide Show</h1>
    <p><img id="slide" alt="Slide show image"></p>
    <p><img id="forward" src="forward_arrow.gif" alt="Forward"></p>
  </body>
</html>

Figure 4. The code!

Let’s look at the HTML first. Line 28 is the <img> that shows a photo. Notice that the <img> tag has id and alt attributes. The id will let us mess with the image in JavaScript. The alt is needed for the page to validate.

But there’s no src attribute in line 28. That’s because the src in set in JavaScript. Its value changes with each click.

Line 29 is the thing that users’ click on. I found the image in a clip art library I bought. The <img> tag in line 29 also has an id, because I want to attach an event to it.

The CSS for this image is in lines 7 to 9. #forward means “Find the thing with an id of forward.” The style sets the mouse cursor to the pointer, which by default looks like a hand.

Now for the JavaScript. Line 14 creates the variable slide_number, and sets its initial value to 1. This variable will go up by one every time the user clicks on the arrow.

Line 15 is:

$("#slide").attr("src", "slide" + slide_number + ".jpg");

$("#slide") says “Find everything with an id of slide.” There is only one thing with that id. Again, don’t forget the #.

"slide" + slide_number + ".jpg" computes the name of the file to show in the <img>. If slide_number is 1, then this works out to slide1.jpg. If slide_number is 4, then this works out to slide4.jpg.

The attr() function sets an attribute of a tag. There are lots of different attributes, so you need to tell attr() which one to set. Then you give it the value.

In English, this:

$("#slide").attr("src", "slide" + slide_number + ".jpg");

says:

Find the thing with an id of slide. Set its src attribute to the value "slide" + slide_number + ".jpg".

Line 16 binds code to the click() event of the forward arrow. So the code from lines 17 to 21 is run whenever the user clicks on the arrow.

Line 17 adds one to the variable slide_number. That’s what ++ does – add one to a variable. You could also write:

slide_number = slide_number + 1;

That says “Take the value of the variable slide_number, add 1 to it, and put the result into the variable slide_number.” It’s common for variables to overwrite their own values like this.

What happens when the user gets to the last slide (slide 4), and clicks on the forward image? There are no more slides! So, back to slide 1. Here’s the if statement:

if ( slide_number > 4 ) {
  slide_number = 1;
}

When slide_number > 4 is true, run the code in the braces. This sets slide_number back to 1.

Finally, line 21 changes the src attribute of the <img> tag, to show the right slide. It’s the same code as line 15.

W00f!

Tracking program execution

I’ll change the JS to this:

$(document).ready(function() {
var slide_number = 1;
$("#slide").attr("src", "slide" + slide_number + ".jpg");
$("#forward").click(function() {
  slide_number ++;
  alert("slide_number before if: " + slide_number);
  if ( slide_number > 4 ) {
    slide_number = 1;
  }
  alert("slide_number after if: " + slide_number);
  $("#slide").attr("src", "slide" + slide_number + ".jpg");
  alert("Slide file name: " + "slide" + slide_number + ".jpg")
});

Figure 5. alert()

Please try it. Notice how The alert() statements show how the program is working.

This is especially handy if there’s a bug in the program. It helps you understand what the program is doing. You can compare what you see to what you expect to see. For example, if you expect slide_number to change from 5 to 1, and it doesn’t, that’s a clue that there might be something wrong with the if.

Exercise: A slideshow

Create your own slide show of at least eight images.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Enhance the slide show

Let’s make some improvements.

Show the slide number

First, let’s show the slide number. Try my solution.

I added this to the HTML, creating a place to show the slide number:

<p>Slide number <span id="slide_number"></span>.</p>

Recall that <span> creates a spot on the page you can refer to with its id.

The I added this to the JavaScript:

$("#slide_number").text(slide_number);

I added it twice, after lines 15 and 21 of Figure 4.

Add a back button

Next I added a button to go backward in the slide show. 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>Slide Show</title>
    <style type="text/css">
      #forward, #backward {
        cursor: pointer;
      }
    </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() {
        var slide_number = 1;
        $("#slide").attr("src", "slide" + slide_number + ".jpg");
        $("#slide_number").text(slide_number);
        $("#forward").click(function() {
          slide_number ++;
          if ( slide_number > 4 ) {
            slide_number = 1;
          }
          $("#slide").attr("src", "slide" + slide_number + ".jpg");
          $("#slide_number").text(slide_number);
        });
        $("#backward").click(function() {
          slide_number --;
          if ( slide_number < 1 ) {
            slide_number = 4;
          }
          $("#slide").attr("src", "slide" + slide_number + ".jpg");
          $("#slide_number").text(slide_number);
        });
      });
    </script>
  </head>
  <body>
    <h1>Slide Show</h1>
    <p><img id="slide" alt="Slide show image"></p>
    <p>Slide number <span id="slide_number"></span>.</p>
    <p>
      <img id="backward" src="backward_arrow.gif" alt="Backward">
      <img id="forward" src="forward_arrow.gif" alt="Forward">
    </p>
  </body>
</html>

Figure 6. Going backward

Look at line 7. This tells the browser to apply the same CSS rule to two different things. Don’t forget the ,.

Line 26 shows the — operator. It subtracts 1 from a variable.

Lines 27 and 28 make sure that slide_number does not go below 1.

Exercise: Improve your slideshow

Improve the slide show you made. Add:

  • Slide number.
  • Back button.
  • Home button. It always takes you back to the first slide.

Add JavaScript alert() statements so that you can see how the program works.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Adding image descriptions

Let’s add a description to each image, so that the user knows what s/he is looking at. Please try the page.

There are many ways to show the descriptions. I’ll use one of the easiest ways.

I’ll change the HTML so that it looks like this:

<body>
  <h1>Slide Show</h1>
  <p><img id="slide" alt="Slide show image"></p>
  <p>Slide number <span id="slide_number"></span>.</p>
  <p id="description_1" class="description">Renata as a puppy, chewing on a human's feet.</p>
  <p id="description_2" class="description">Renata wondering what is going on.</p>
  <p id="description_3" class="description">Renata loves to chase balls.</p>
  <p id="description_4" class="description">What's that? Can I eat it?</p>
  <p>
    <img id="backward" src="backward_arrow.gif" alt="Backward">
    <img id="forward" src="forward_arrow.gif" alt="Forward">
  </p>
</body>

Figure 7. HTML for image descriptions

There’s an important difference in the way I’ve implemented the slides and the descriptions. There is one tag for all the slides. It’s the <img> tag on line 44. To show a slide, we change the contents of that one tag.

The way descriptions are handled in Figure 7 is different. There are four tags for the descriptions, a separate one for each description. They’re on lines 46 to 49. To show a description, we change which tag is showing.

So if we want to show the description of slide 1, we show the element with the id of description_1 (line 46), and hide the other descriptions. To show the description of slide 2, we show the element with the id of description_2 (line 47), and hide the other descriptions.

Renata
Renata

Wait a minute. The code is wrong.

Kieran
Kieran

Where’s that?

Renata
Renata

Look at line 46. It has an id and a class. Can you do that?

Kieran
Kieran

Sure. That’s part of how the code works. We’ll talk about that in a bit.

Let’s look again at what happens when a user clicks on the “Next slide” button. Just the logic of it, not the code, not just yet.

Increase the slide number by one.
If the slide number is more than 4, make it 1.
The new slide name is (slide + slide number + .jpg).
Set the <img> tag's src to the slide name.
Hide all of the descriptions.
Show the element (description_ + slide number).

As before, the first two lines work out which slide number the user wants to see. The next two lines show that slide. The last two lines show the description. The last line uses the slide number.

So the slide number is used for two things:

  • Select the photo to show, and
  • Select the description to show.

Here’s the new JavaScript.

<script type="text/javascript">
  $(document).ready(function() {
    var slide_number = 1;
    $("#slide").attr("src", "slide" + slide_number + ".jpg");
    $("#slide_number").text(slide_number);
    $(".description").hide();
    $("#description_" + slide_number).show();
    $("#forward").click(function() {
      slide_number ++;
      if ( slide_number > 4 ) {
        slide_number = 1;
      }
      $("#slide").attr("src", "slide" + slide_number + ".jpg");
      $("#slide_number").text(slide_number);
      $(".description").hide();
      $("#description_" + slide_number).show();
    });
    $("#backward").click(function() {
      slide_number --;
      if ( slide_number < 1 ) {
        slide_number = 4;
      }
      $("#slide").attr("src", "slide" + slide_number + ".jpg");
      $("#slide_number").text(slide_number);
      $(".description").hide();
      $("#description_" + slide_number).show();
    });
  });
</script>

Figure 8. New JavaScript

Most of its the same as before. Let’s take a look.

When the page first loads, we want slide number 1 to be showing. That’s what lines 14 to 18 do. Line 14 creates a variable and sets it to 1. Line 15 shows that slide. Line 16 outputs the number of that slide.

Lines 17 and 18 are new. Here’s line 17:

$(".description").hide();

Remember that the . means class. So the line says.

Hide everything that has a class of description.

All four of the description elements have the class description. Here they are:

<p id="description_1" class="description">Renata as a puppy, chewing on a human's feet.</p>
bq. <p id="description_2" class="description">Renata wondering what is going on.</p>
bq. <p id="description_3" class="description">Renata loves to chase balls.</p>
bq. <p id="description_4" class="description">What's that? Can I eat it?</p>

So line 17 will hide all of the descriptions.

Once we’ve done that, we want to show just the description of the current slide. So line 18 is:

$("#description_" + slide_number).show();

Remember that # means id. So since slide_number is 1, this means:

Show the element with an id of description_1.

Renata
Renata

Oh, snap! That’s why each of the descriptions has an id and a class. The ids are all different. They have to be; you can’t reuse the same id on a page. The classes are all the same.

Kieran
Kieran

Right.

Renata
Renata

You use the class to refer to them all in one statement. Then you can hide everything at once.

Kieran
Kieran

Indeed.

Renata
Renata

And you use the id to refer to just one of them. Because you only want to show one at a time.

Kieran
Kieran

Aye! You got it!

Summary

On this page, you learned how to control a sequence using events, with a variable keeping track of where the page is in the sequence.

What now?

Now it’s time to do some more exercises. Yay!

Exercises: A Web page with images

You should do the four recommended exercises. Do the optional exercises if you want more practice.

Exercises in the Explore section are more challenging. You may need to use HTML and CSS that isn’t covered in CoreDogs. Get ready to Google!

Recommended

Exercise: Three dogs

Here are some images. Right-click and save to download them to your computer.

Kieran

CC

Renata

Background

Use them to create a page that looks like this:

Output

Hints:

  • Here’s some HTML: <p><img id="kieran" src="kieran.jpg" alt="Kieran"></p>
  • You can use # in CSS to select an item with a given id.
  • Don’t use text-align. The last image does not go all the way to the right. It just gets indented more.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: The best animal

Download these three images:

Cat

Dog

Horse

Write a page that starts looking like this:

Start state

When the user clicks on the cat or the horse:

Incorrect

When the user clicks on the dog:

Correct

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Money counter

Download these images to your computer:

One dollar bill

Two dollar bill

Five dollar bill

Ten dollar bill

Write a page that shows the images. When the user clicks on an image, the page updates a total by the appropriate amount. Here’s some sample output:

Output

Hint: I used pseudocode like this:

When someone clicks on a bill:
Get the current total from the page.
Add the bill's value to the total.
Show the new total on the page.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Optional

Exercise: A dog slideshow

Make a slideshow of dog photos with captions. Your show should be at least four slides long.

  • Find some dog images that you can legally use.
  • Add funny captions to them with a graphics program.
  • Make a slideshow page with forward and back arrows that work. Find images you can legally use.
  • Show a text caption below each image, as well as the one on the image itself.
  • Use seamless tiles for the page background.
  • Add a header to the page. Use seamless tiles for the header area as well.
  • Add borders around the header and photo.

Here is a page sample. Use different images and captions for your solution:

Sample

Figure 1. Sample

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exploding tennis balls

Most of us dogs like to chase tennis balls. Renata loves it. But you have to be careful.

Create a page that starts off like this:

Start state

Figure 1. Start state

The user clicks on a tennis ball. If the ball is safe, then the page adds one to the number of balls clicked:

One safe click

Figure 2. One safe click

The user clicks another ball. If that’s safe:

Two safe clicks

Figure 3. Two safe clicks

The count keeps going up, as long as the user clicks on safe balls. But if the user clicks on an exploding ball:

Boom

Figure 4. Boom!

How does your code know whether a ball is safe? By the class. Here’s some HTML:

<img class="safe" src="ball.jpg" alt="Toy">
<img class="safe" src="ball.jpg" alt="Toy">
<img class="boom" src="ball.jpg" alt="Toy">
<img class="safe" src="ball.jpg" alt="Toy"><br>

Figure 5. First row of balls

Three of balls have a class of safe. One has a class of boom. Click on a safe ball, and the number of balls gets updated. Click on a boom ball, and the Boom! message appears.

Here’s the photo:

Ball

Upload your solution to your server, and paste the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Explore

These challenging exercises may use HTML not covered in CoreDogs. Get ready to Google!

Exercise: Tic tac toe game

Create a two-player tic tac toe game. Two people take turns clicking on the grid.

This video explains.

One more thing. If a cell already has an X or O in it, clicking it does nothing.

Here are three images you can use:

X

O

Blank

Before you start, read this article.

Some code that might help:

  <script type="text/javascript">
    var turn = "x";
    var turn_count = 0;
    $(document).ready(function() {

The variables turn and turn_count are declared outside $(document).ready(). They’ll keep their values between clicks.

Upload your solution to your server. Enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: New tic tac toe game

Improve the tic tac toe game.

  1. Add a New Game button, that resets the game back to the beginning.
  2. Keep track of the number of games played. Show that on the page.

Upload your solution to your server. Enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

A page with tables

You know how to create pages, add text, interact with the user, and add images. We’re on our way to making complete Web sites.

This lesson looks at the HTML tags for tables. Tables make it easy to present data in rows and columns. Here’s an example:

Dog Size Breed
Kieran Large Lab
CC Medium Sheltie
Renata Medium Coonhound/lab mix

Tables are important for many Web sites. Use them for schedules, price lists, statistical information, ... anything you like.

This lesson will show you how to create tables, style them, and let the user interact with them.

Let’s go!

Basic tables

This page’s goals

By the end of this page, you should:

  • Be able to create a basic table.
  • Add a header and footer.

Basic tables

Here’s a table listing some university classes:

Table example

Figure 1. Table example

It’s hard to see the rows and columns, so let me add some lines.

Table example with borders

Figure 2. Table example with borders

You can see that the table has two rows and three columns. That’s what makes a table a table: rows and columns.

Here’s the code for the table (like Figure 1, with no borders).

<table>
  <tr>
    <td>DOG 101</td>
    <td>Introduction to the modern dog</td>
    <td>MW 9:00am - 11:00am</td>
  </tr>
  <tr>
    <td>DOG 110</td>
    <td>Dogs in the ancient world</td>
    <td>M 6:30pm - 9:30pm</td>
  </tr>
</table>

Figure 3. Code for a simple table.

The whole thing is surrounded with <table> tags: lines 1 and 12.

Each row is inside a <tr> tag pair. The first row is from lines 2 to 6, the second from lines 7 to 11.

Inside each <tr>, there is a <td> pair for each table cell. The “d” in <td> stands for “data.” There’s one <td> for each column.

Here’s some more code:

<table>
  <tr>
    <td>a</td>
    <td>0.00</td>
    <td>0.01</td>
    <td>0.02</td>
    <td>0.03</td>
    <td>0.04</td>
    <td>0.05</td>
  </tr>
  <tr>
    <td>0.0</td>
    <td>0.0000</td>
    <td>0.0040</td>
    <td>0.0080</td>
    <td>0.0120</td>
    <td>0.0160</td>
    <td>0.0199</td>
  </tr>
  <tr>
    <td>0.1</td>
    <td>0.0398</td>
    <td>0.0438</td>
    <td>0.0478</td>
    <td>0.0517</td>
    <td>0.0557</td>
    <td>0.0596</td>
  </tr>
  <tr>
    <td>0.2</td>
    <td>0.0793</td>
    <td>0.0832</td>
    <td>0.0871</td>
    <td>0.0910</td>
    <td>0.0948</td>
    <td>0.0987</td>
  </tr>
  <tr>
    <td>0.3</td>
    <td>0.1179</td>
    <td>0.1217</td>
    <td>0.1255</td>
    <td>0.1293</td>
    <td>0.1331</td>
    <td>0.1368</td>
  </tr>
</table>

Figure 4. Another table

It looks like this in a browser:

Another table

Figure 5. Another table – rendered

Extra math points if you know what this is, or can figure it out. Hint: it’s part of a probability distribution.

Exercise: Color table

Create a table that looks like this:

Color table

Upload your solution to your server. Enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Here’s the table of university classes again:

Table example

Figure 1 (again). Table example

It might help to add a header, so users know what the columns are. A footer can come in handy, too. How about this:

Table example with header and footer

Figure 6. Header and footer

Here’s the code:

<table>
  <thead>
    <tr>
      <th>Course code</th>
      <th>Title</th>
      <th>When offered</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>DOG 101</td>
      <td>Introduction to the modern dog</td>
      <td>MW 9:00am - 11:00am</td>
    </tr>
    <tr>
      <td>DOG 110</td>
      <td>Dogs in the ancient world</td>
      <td>M 6:30pm - 9:30pm</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td colspan="3">Times subject to change.</td>
    </tr>
  </tfoot>
</table>

Figure 7. Code for header and footer

The table is divided into three parts: the header, the body, and the footer. The header is from lines 2 to 8. The body is from lines 9 to 20. The footer is from lines 21 to 25.

The header uses the tag <th> instead of <td>. The h stands for “header,” as you might imagine. By default, browsers render <th> as centered and bold.

For the footer, I could have left out the colspan:

<tfoot>
  <tr>
    <td>Times subject to change.</td>
  </tr>
</tfoot>

Figure 8. Bad footer

It would have looked like this:

Bad footer rendered

Figure 9. Bad footer – rendered

The browser expanded all of the cells in the first column to fit the content in the footer. That gives too much space in the first two rows of the first column.

Instead, I did this:

<tfoot>
  <tr>
    <td colspan="3">Times subject to change.</td>
  </tr>
</tfoot>

Figure 10. Good footer

colspan="3" tells the browser that the first <td> covers three columns in the table. There’s enough room for “Times subject to change.” W00f!

Exercise: Color table with header and footer

Add a header and footer to your color table:

Color table with header and footer

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

On this page you learned how to create a basic table, and add a header and footer.

What now?

Let’s style the tables. We’ll give them a CSS makeover.

Styling tables

Where are we?

You’ve learned how to create basic tables, with rows and columns. You know how to add headers and footers. But they don’t look great. Let’s fix that with CSS.

This page’s goals

By the end of this page, you should:

  • Be able to add spacing around tables and cells.
  • Be able to add borders and background colors.
  • Be able to style a table’s header and footer separately from its body.
  • Be able to add striping to a table using jQuery.

Add spacing

Here’s the university course list from earlier:

University courses

Figure 1. University courses

Here’s the code:

<table>
  <thead>
    <tr>
      <td>Course code</td>
      <td>Title</td>
      <td>When offered</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>DOG 101</td>
      <td>Introduction to the modern dog</td>
      <td>MW 9:00am - 11:00am</td>
    </tr>
    <tr>
      <td>DOG 110</td>
      <td>Dogs in the ancient world</td>
      <td>M 6:30pm - 9:30pm</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td colspan="3">Times subject to change.</td>
    </tr>
  </tfoot>
</table>

Figure 2. Code for university courses

The table is made up of boxes:

Table boxes

Figure 3. Table boxes

As you can see, the table is one giant box, with smaller boxes within it. Each box is a cell in the table.

Suppose I want to add more space around the table and the cells:

With spacing

Figure 4. With spacing

I’d change the code to:

...
<style type="text/css">
  #table1 {
    margin: 20px;
    border-spacing: 10px;
  }
  #table1 td {
    padding: 10px;
  }
</style>
...
<table id="table1">
...
</table>
...

Figure 5. Table spacing with CSS

Line 4 adds space around the edges of the entire table. Line 5 adds space around the outside of the cells. Line 8 adds spacing inside the cells, between the edges of the cells and their contents.

Borders and background colors

Suppose I wanted to make the table look like this:

Adding colors

Figure 6. Adding colors

Here’s some code:

...
<style type="text/css">
#table1 {
  color: #585858;
  background-color: #FFFFEE;
  border: 2px solid #683900;
  margin: 10px;
  border-spacing: 2px;
}
#table1 td {
  border: 1px dotted #AB5500;
  padding: 2px;
}
</style>

Figure 6. Code to add colors

There’s a lot you can do with colors and spacing. You can experiment with Somacon’s HTML and CSS Table Border Style Wizard.

When you use <thead>, <tbody>, and <tfooter> tags, you can easily give the header and footer of a table a different look from the footer.

Suppose I wanted to make this:

Header and footer styling

Figure 7. Header and footer styling

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>Table example</title>
    <style type="text/css">
      #table1 {
        color: #585858;
        border-spacing: 5px;
      }
      #table1 tbody td {
        background-color: #FFFFCC;
        padding: 4px;
      }
      #table1 thead td, #table1 tfoot td {
        color: #FFFFCC;
        background-color: #683900;
        padding: 4px;
      }
    </style>
  </head>
  <body>
    <table id="table1">
      <thead>
        <tr>
          <td>Course code</td>
          <td>Title</td>
          <td>When offered</td>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>DOG 101</td>
          <td>Introduction to the modern dog</td>
          <td>MW 9:00am - 11:00am</td>
        </tr>
        <tr>
          <td>DOG 110</td>
          <td>Dogs in the ancient world</td>
          <td>M 6:30pm - 9:30pm</td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="3">Times subject to change.</td>
        </tr>
      </tfoot>
    </table>
  </body>
</html>

Figure 8. Code for header and footer styling

The rule in lines 7 to 10 sets text color and border spacing for the entire table. Lines 11 to 14 styles the body of the table. Lines 15 to 19 style the header and footer, giving them the same style.

Look at the selector on line 15:

#table1 thead td, #table1 tfoot td

The comma (,) in the middle says that the rule should be applied to two things. The first thing is the set of <td> tags in the <thead> of the element with the id of table1 (remember: # says “look at the id attribute”). The second thing in the selector – after the comma – is the set of <td> tags in the <tfoot> of the element with the id of table1.

Exercise: Styling the color table

Style your color table so that it looks like this:

Styled color table

Upload your solution to your server. Enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Table striping

On the previous page, we had a table of numbers that looked like this:

Another table

Figure 9. Table o’ numbers

Suppose I wanted to make it look like this:

Striping

Figure 10. Striping

Easy to do with some jQuery magic. Here’s the code for 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>Normal distribution</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <style type="text/css">
      body {
        font-family: Verdana, Helvetica, sans-serif;
        font-size: 12px;
        color: #585858;
      }
      .probability_table {
        border-spacing: 4px;
        text-align: right;
      }
      .probability_table td {
        padding: 4px;
      }
      .probability_table thead {
        color: white;
        background-color: #585858;
      }
      .odd_row {
        background-color: #DDDDDD;
      }
    </style>
    <script type="text/javascript">
      $(document).ready(function() {
        $(".probability_table tbody tr:odd").addClass("odd_row");
      });
    </script>
  </head>
  <body>
    <table class="probability_table">
      <thead>
        <tr>
          <td>a</td>
          <td>0.00</td>
          <td>0.01</td>
          <td>0.02</td>
          <td>0.03</td>
          <td>0.04</td>
          <td>0.05</td>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>0.0</td>
          <td>0.0000</td>
          <td>0.0040</td>
          <td>0.0080</td>
          <td>0.0120</td>
          <td>0.0160</td>
          <td>0.0199</td>
        </tr>
        <tr>
          <td>0.1</td>
          <td>0.0398</td>
          <td>0.0438</td>
          <td>0.0478</td>
          <td>0.0517</td>
          <td>0.0557</td>
          <td>0.0596</td>
        </tr>
        <tr>
          <td>0.2</td>
          <td>0.0793</td>
          <td>0.0832</td>
          <td>0.0871</td>
          <td>0.0910</td>
          <td>0.0948</td>
          <td>0.0987</td>
        </tr>
        <tr>
          <td>0.3</td>
          <td>0.1179</td>
          <td>0.1217</td>
          <td>0.1255</td>
          <td>0.1293</td>
          <td>0.1331</td>
          <td>0.1368</td>
        </tr>
      </tbody>
    </table>
  </body>
</html>

Figure 11. Striping page

Let’s go over the code. Lines 35 to 85 are the HTML for the table. I gave the table a class of probability_table.

Renata
Renata

Can I ask a question?

Kieran
Kieran

Indeed!

Renata
Renata

In other examples, you gave tables ids. But you’ve given this one a class. Why?

Kieran
Kieran

Good question. Let me explain.

Renata noticed that in other cases, I’ve given tables ids, like this:

<table id="table1">

Why use class here? Because when I imagine a site that has number tables, there could be more than one number table on each page. Remember that I can only use a particular id once on a page. But I can use the same class many times. By using class, I can have one set of CSS rules that will apply to all of the number tables on a page.

This is how Webers think about their work. “Since there can be more than one number table on a page, how should I code it to reduce development costs, and make changes to the site easy and cheap?” Your employers and clients will thank you for thinking this way.

Let’s go back to the code. You can see that I’ve added <thead> (line 36) and <tbody> (line 47) tags, so I can style those parts separately. This table doesn’t need a separate footer.

Here’s how the header is colored:

.probability_table thead {
  color: white;
  background-color: #585858;
}

Figure 12. Header colors

The text color is white, and the background is gray.

Any color code that has the same values for red, green, and blue will show as gray. The lower the value you use, the darker the gray. So rgb(50, 50, 50) is a dark gray, and rgb(200, 200, 200) is a lighter gray.

The striping is done with jQuery. Let’s focus on that:

...
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<style type="text/css">
...
  .probability_table td {
    padding: 4px;
  }
...
  .odd_row {
    background-color: #DDDDDD;
  }
</style>
<script type="text/javascript">
  $(document).ready(function() {
    $(".probability_table tbody tr:odd").addClass("odd_row");
  });
</script>
...

Figure 13. Striping with jQuery

Line 2 adds the jQuery code, fetching it from Google. You need to do this before you can do any jQuery magic.

Lines 14 to 16 do the striping. Remember that $(document).ready() runs when the page has been loaded. It contains one line:

$(".probability_table tbody tr:odd").addClass("odd_row");

The selector says “Find every element with a class of probability_table. Within them, find every <tbody> element. Then select all of the odd numbered <tr>s.”

Then, for all of the elements that the selector returns (which will be all the odd numbered rows in elements with a class of probability_table), add the class odd_row. This class is defined in lines 9 to 11. It sets the background color to gray.

Renata
Renata

Another question.

Kieran
Kieran

What’s that?

Renata
Renata

You have <thead> and <tbody> in the HTML. So you can style the table head and body separately.

Kieran
Kieran

Right.

Renata
Renata

But look at the rule at lines 5 to 7. It has a <td> in it, but no <thead> and <tbody>. What’s the deal?

Kieran
Kieran

Ooo, another good question.

The rule in lines 5 to 7 applies to all <td>s in the table, no matter where they are. If I were to change line 6 to, say, 10 pixels, all the cells in the table would change, no matter whether they were in the head or the body of the table. This helps me keep things consistent.

CC
CC

Hmm, let’s see if I have things straight.

Kieran
Kieran

OK.

CC
CC

Can we look at the output again?

Kieran
Kieran

OK. Here it is.

Striping

Figure 10 (again). Striping

CC
CC

The cell with the “a” in it, the one in the top left. It looks like it has a gray background, white text, and 4 pixels of padding. Is that right?

Kieran
Kieran

Yes.

CC
CC

But no single rule specifies that. So are the rules combined?

Kieran
Kieran

Yes! The font-family and font-size come from one rule. The text-align comes from another. The padding comes from yet another. And a different rule gives the colors.

This is normal in CSS work. The Weber figures out what aspects of a look go with what elements. The typeface is to be the same on the entire page, so it gets attached to the <body> tag. The text-alignment is to be the same for the entire table, so it gets attached to the <table> tag.

CC
CC

I can see how that would make the page easier to change. Like, change one number on line 6, and the padding changes in the entire table. For the header and the body. And the footer, if there was one.

Kieran
Kieran

Right!

CC
CC

But that’s a lot to think about.

Kieran
Kieran

It seems like that when you’re learning, but not when you actually do it. CSS fits naturally with the way we think about tables, with things (like cells) inside things (like rows) inside things (like a table body). It ends up being intuitive, once you’ve done it a few times.

Exercise: Striping the color table

Make your color table look like this:

Striping

Hint: odd or even?

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

On this page, you learned how to:

  • Add spacing around tables and cells.
  • Add borders and background colors.
  • Style a table’s header and footer separately from its body.
  • Add striping to a table using jQuery.

W00f!

What now?

How about a table for your eMe?

eMe: Your own table

Where are we?

You know how to make a table. You know how to style one. Time to make one for your own site.

What about?

Make a table about something on your interesting stuff list. For example, I might make a table about Buffy, like this:

Season U.S. ratings
1 3.7 million
2 5.2 million
3 5.3 million
4 4.7 million
5 4.4 million
6 4.6 million
7 3.6 million

Choose something, and make a table about it. Style it any way you want. Border or not. Background color. Whatever suits your fancy.

If you want, you can put images in your table.

Summary

  • You made a table for your eMe.

What now?

Let’s make an interactive table. The user clicks, and something happens.

Interactive tables - sorting

Where are we?

You know how to create and style tables. Let’s make tables interactive.

This page’s goals

By the end of this page, you should be able to make a table sortable. Users will be able to click on table columns to sort tables the way they want. You’ll use a jQuery plugin to do the work.

Understanding the task

Suppose Ted and Fred both want to buy dog toys. Ted wants the best he can find. Fred just wants something cheap.

Ted and Fred visit a site that sells dog toys. Ted wants a good toy, so he’d like to see the toys with the highest ratings listed first:

Sort by rating

Figure 1. Sort by rating

Fred wants to see the cheapest toys listed first:

Sort by price

Figure 2. Sort by price

We can give them both what they want by letting them choose how they want the table sorted. They could click on the column titles to sort. You can try the page.

jQuery plugins

A plugin is a JavaScript program that you can add to jQuery. It extends jQuery, that is, makes jQuery do something extra. There are hundreds of plugins, for everything from graphing, image handling, chat, ..., well, you name it. You can check the list.

There are three steps to using a plugin:

  1. Add the plugin JS file to your page.
  1. Set up the HTML and CSS the plugin needs.
  1. Call the plugin.

Adding the plugin

A plugin is just a JavaScript file. You add it to your page like any other JS file: with a <script> tag in the header.

Set up your HTML and CSS

Some plugins require special set up in HTML or CSS. But you’ve seen that before. Take the jQuery function addClass(). (It’s a normal part of jQuery, not from a plugin.) It adds a class to an element.

Suppose we had this code:

$("#best_dog").addClass("champion");

It tells JS to find an element with the id best_dog, and add the class champion to it.

The code isn’t going to work if you haven’t already set up an element with the id best_dog in the HTML, and created a class called champion in the CSS.

The same thing with plugins. You can’t tell a plugin to graph some data if you don’t tell it what data to graph. You can’t tell a plugin to shrink an image if you don’t tell it what image to shrink.

That’s what I mean by “set up your HTML and CSS.” You need to prepare the things that the plugin will manipulate.

Calling the plugin

Once you’ve added a plugin, you treat it as if it was built-in to jQuery. Most plugins create new functions, like drawGraph() or playSound(). You call the functions, as if they were part of jQuery to begin with.

Using tablesorter

Let’s do these three things with the tablesorter plugin:http://tablesorter.com/. It lets users click on column headers to sort a table.

Adding the plugin

Normally, you would download the plugin to your computer, and then upload it to your server. Some plugins also come with CSS files, images, and other things that you need to upload. Look at the plugin’s documentation to figure out exactly what to do with it.

tablesorter needs just one JS file. For convenience, I’ve put the file on CoreDogs. You can add it to your pages by inserting the following line in the <head> section of each page you want to use it on.

<script type="text/javascript" src="http://coredogs.com/resources/jquery.tablesorter-2.0.3.min.js"></script>

Figure 3. Adding tablesorter

Do this with your live projects, if you want.

Set up your HTML and CSS

tablesorter requires that you:

  • Use <thead> and <tbody> tags in your table.
  • Use <th> tabs inside <thead>.
  • Use <td> tabs inside <tbody>.

Here’s some code for the dog toys table. It doesn’t do any sorting yet – it’s just to get us started.

<table>
  <thead>
    <tr>
      <th>Catalog<br>number</th>
      <th>Name</th>
      <th>Photo</th>
      <th>Average<br>rating</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>243243</td>
      <td>Ball of Chasing</td>
      <td><img src="ball.jpg" alt="Ball of chasing"></td>
      <td>3.9</td>
      <td>4.99</td>
    </tr>
    <tr>
      <td>593922</td>
      <td>Blue Chewey</td>
      <td><img src="blue_chewey.jpg" alt="Blue chewey"></td>
      <td>4.8</td>
      <td>12.99</td>
    </tr>
    <tr>
      <td>293944</td>
      <td>Cookie Bone</td>
      <td><img src="cookie_bone.jpg" alt="Cookie bone"></td>
      <td>3.5</td>
      <td>3.99</td>
    </tr>
    <tr>
      <td>948322</td>
      <td>Cookie Car</td>
      <td><img src="cookie_car.jpg" alt="Cookie car"></td>
      <td>3.6</td>
      <td>3.99</td>
    </tr>
    <tr>
      <td>882030</td>
      <td>Cookie Hydrant</td>
      <td><img src="cookie_hydrant.jpg" alt="Cookie hydrant"></td>
      <td>3.2</td>
      <td>3.99</td>
    </tr>
    <tr>
      <td>323822</td>
      <td>Cookie Shoe</td>
      <td><img src="cookie_shoe.jpg" alt="Cookie shoe"></td>
      <td>4.1</td>
      <td>3.99</td>
    </tr>
    <tr>
      <td>392866</td>
      <td>Rope Twist</td>
      <td><img src="rope.jpg" alt="Rope twist"></td>
      <td>4.3</td>
      <td>11.99</td>
    </tr>
    <tr>
      <td>298882</td>
      <td>Chew Shoes</td>
      <td><img src="shoes.jpg" alt="Chew shoes"></td>
      <td>2.1</td>
      <td>17.95</td>
    </tr>
  </tbody>
</table>

Figure 4. Initial toy code

Everything should be familiar. There’s a head (lines 2 to 10), and a body (lines 11 to 68). The head has one table row. Each column heading uses the <th> tag. The tablesorter plugin needs <th>s so it can identify column headings.

Each row in the body describes a single product. The third column has an image with a thumbnail photo of the product.

The table looks like this so far:

Unstyled table

Figure 5. Unstyled table

We want to add CSS styles to make it look like this:

Styled table

Figure 6. Styled table

We have to make some changes:

Unstyled table changes

Figure 7. Unstyled table changes

The font family, size, and color needs to be changed for all the text. The header needs to have its color flipped around: white text on a dark background. The cells with number values – rating and price – need to be aligned to the right. The cells in the body need a border.

Here’s some code to do the job:

<!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>Sorting a table</title>
    <style type="text/css">
      body {
        font-family: Verdana, Helvetica, sans-serif;
        font-size: 12px;
        color: #585858;
      }
      #dog_toys {
        border-spacing: 3px;
      }
      #dog_toys thead th {
        color: white;
        background-color: #683900;
        padding: 4px;
      }
      #dog_toys tbody td {
        border: 1px dotted #683900;
        padding: 2px;
      }
      #dog_toys tbody td.catalog_id {
        text-align: center;
      }
      #dog_toys tbody td.photo {
        text-align: center;
      }
      #dog_toys tbody td.rating {
        text-align: center;
      }
      #dog_toys tbody td.price {
        text-align: right;
      }
    </style>
  </head>
  <body>
    <table id="dog_toys">
      <thead>
        <tr>
          <th>Catalog<br>number</th>
          <th>Name</th>
          <th>Photo</th>
          <th>Average<br>rating</th>
          <th>Price</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="catalog_id">243243</td>
          <td class="name">Ball of Chasing</td>
          <td class="photo"><img src="ball.jpg" alt=""></td>
          <td class="rating">3.9</td>
          <td class="price">4.99</td>
        </tr>
        <tr>
          <td class="catalog_id">593922</td>
          <td class="name">Blue Chewey</td>
          <td class="photo"><img src="blue_chewey.jpg" alt="Blue chewey"></td>
          <td class="rating">4.8</td>
          <td class="price">12.99</td>
        </tr>
        <tr>
          <td class="catalog_id">293944</td>
          <td class="name">Cookie Bone</td>
          <td class="photo"><img src="cookie_bone.jpg" alt="Cookie bone"></td>
          <td class="rating">3.5</td>
          <td class="price">3.99</td>
        </tr>
        <tr>
          <td class="catalog_id">948322</td>
          <td class="name">Cookie Car</td>
          <td class="photo"><img src="cookie_car.jpg" alt="Cookie car"></td>
          <td class="rating">3.6</td>
          <td class="price">3.99</td>
        </tr>
        <tr>
          <td class="catalog_id">882030</td>
          <td class="name">Cookie Hydrant</td>
          <td class="photo"><img src="cookie_hydrant.jpg" alt="Cookie hydrant"></td>
          <td class="rating">3.2</td>
          <td class="price">3.99</td>
        </tr>
        <tr>
          <td class="catalog_id">323822</td>
          <td class="name">Cookie Shoe</td>
          <td class="photo"><img src="cookie_shoe.jpg" alt="Cookie shoe"></td>
          <td class="rating">4.1</td>
          <td class="price">3.99</td>
        </tr>
        <tr>
          <td class="catalog_id">392866</td>
          <td class="name">Rope Twist</td>
          <td class="photo"><img src="rope.jpg" alt="Rope twist"></td>
          <td class="rating">4.3</td>
          <td class="price">11.99</td>
        </tr>
        <tr>
          <td class="catalog_id">298882</td>
          <td class="name">Chew Shoes</td>
          <td class="photo"><img src="shoes.jpg" alt="Chew shoes"></td>
          <td class="rating">2.1</td>
          <td class="price">17.95</td>
        </tr>
      </tbody>
    </table>
  </body>
</html>

Figure 8. Added styles

The changes in the look are all made by CSS. But I changed the HTML as well. Why? To create things I could hook the CSS rules to.

Changing the HTML

I wanted to make it easy to hook CSS rules to the things that needed to change their look. Here’s what I did.

<table id="dog_toys">
  <thead>
	<tr>
	  <th>Catalog<br>number</th>
	  <th>Name</th>
	  <th>Photo</th>
	  <th>Average<br>rating</th>
	  <th>Price</th>
	</tr>
  </thead>
  <tbody>
	<tr>
	  <td class="catalog_id">243243</td>
	  <td class="name">Ball of Chasing</td>
	  <td class="photo"><img src="ball.jpg" alt="Ball of chasing"></td>
	  <td class="rating">3.9</td>
	  <td class="price">4.99</td>
	</tr>
	<tr>
	  <td class="catalog_id">593922</td>
	  <td class="name">Blue Chewey</td>
	  <td class="photo"><img src="blue_chewey.jpg" alt="Blue chewey"></td>
	  <td class="rating">4.8</td>
	  <td class="price">12.99</td>
	</tr>
...
  </tbody>
</table>

Figure 9. Adding names to the HTML

First, I gave the table an id (line 1). As we will see, this is enough for almost all of the CSS rules I need to make.

But some of the columns needed special treatment. For example, the body’s photo column needs to be centered. And the price needs to be aligned to the right.

The price is right? Ack! Bad pun! Boo!

I gave each column (each <td> tag) a class. Then I could style the classes to get the alignment I wanted (center, right, whatever). You can see this on line 13, 14, and so on.

CC
CC

You gave the table an id on line 1, but on line 13 you gave the <td> a class. Why not give the <td> an id as well? Like <td id="catalog_id">. Wouldn’t that be more consistent?

Renata
Renata

Oo, oo, I know!

Kieran
Kieran

Go ahead, Renata.

Renata
Renata

Because you can only use the same id once per page. If you used <td id="catalog_id"> on line 13, you couldn’t do that again on line 20.

Kieran
Kieran

That’s right! If you give two things the same id, you might get strange results. But you can use the same class as much as you want.

Adding the CSS

Now that I have the names added to the HTML, I can use them in the CSS.

body {
  font-family: Verdana, Helvetica, sans-serif;
  font-size: 12px;
  color: #585858;
}
#dog_toys {
  border-spacing: 3px;
}
#dog_toys thead th {
  color: white;
  background-color: #683900;
  padding: 4px;
}
#dog_toys tbody td {
  border: 1px dotted #683900;
  padding: 2px;
}
#dog_toys tbody td.catalog_id {
  text-align: center;
}
#dog_toys tbody td.photo {
  text-align: center;
}
#dog_toys tbody td.rating {
  text-align: center;
}
#dog_toys tbody td.price {
  text-align: right;
}

Figure 10. The styles

The rule in lines 1 to 5 sets font information for the entire page. The rest of the rules start with #dog_toys, so they apply only to the table. The rule in lines 6 to 8 applies to entire table. The next rule styles the table header, and the one after that styles the cells in the body. The rest of the rules set the classes of the columns.

Renata
Renata

You added a class to the product name column: <td class="name">. But you didn’t use the class in the CSS. Why?

Kieran
Kieran

Good question. Clients often want changes to pages. I added the name class to make future changes to that column easier.

It isn’t strictly necessary. I could have left it out. That would still be OK.

Exercise: More color table styling

Make your color table look like this:

More styles

The text is right aligned in some of the cells. The text color for the numbers matches the name of the color.

There is no striping. It tends to interfere with the sorting you’ll do later.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Calling the plugin

The last step is to call the plugin. Here’s code to add to the <head> of the page.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://coredogs.com/resources/jquery.tablesorter-2.0.3.min.js"></script>
<script type="text/javascript">
  $(document).ready(function(){ 
    $("#dog_toys").tablesorter(
      { headers: {
        2: {
            sorter: false
        }
      } 
    } ); 
  }); 
</script>

Figure 11. Calling the plugin

Line 1 gets jQuery from Google. Line 2 gets the tablesorter plugin from CoreDogs. Lines 4 to 12 are executed when the page has been loaded into the browser.

Line 5 is where the real action is. To make the table sortable, all I have to do is this:

$("#dog_toys").tablesorter();

This makes every column in the table sortable. The user only needs to click on the column headings.

The problem is, I don’t want all the columns to be sortable. Sorting on the photo column doesn’t make a lot of sense. So I want the plugin to make that column not sortable.

That’s what lines 6 to 10 do. They set options for the headers (line 6), setting the photo column (line 7) to not sortable (line 8).

Why is there a 2 for the photo column (line 7)? That’s the column’s index. The first column is has an index of 0. The second column has an index of 1. The third column has an index of 2. The photo column is the third column, so I use an index of 2 in line 7.

Working out the syntax – what goes where – is messy. I took the easy way out. I found this in the plugin’s documentation:

For example, to disable sorting on the first two columns of a table: headers: { 0: { sorter: false}, 1: {sorter: false} }

I just copied it, changed the 0 to a 2, and got rid of the other column (the 1). I do this whenever I can – look for an example of what I want to do, copy it, and change it if necessary.

You can try the final page.

Exercise: Sorting the color table

Make your color table sortable, on all columns.

Hint: .tablesorter() is enough.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

On this page, you learned how to make sortable tables using a jQuery plugin.

What now?

You’ll do more table exercises on the next page. Make sure you do them! It’s the only way to learn.

Exercises: A Web page with tables

You should do the five recommended exercises. Do the optional exercises if you want more practice.

Exercises in the Explore section are more challenging. You may need to use HTML and CSS that isn’t covered in CoreDogs. Get ready to Google!

Recommended

Exercise: Money images

Make a page that looks like this:

Money images

You can use these images:

One front

One back

Five front

Five back

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Population growth rate

Create a table showing the population growth rate for countries around the world. It should look like this:

Growth rate

The data comes from the CIA World Fact Book.

There’s lots of data. You can copy from a file with the table already created. It will save you a lot of typing.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Population growth rate with stripes

Add stripes to your population growth rate table:

Growth rate striped

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Sortable population growth rate table

Remove the stripes from your table. Then give users the ability to sort your population growth rate table on any column.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Optional

Exercise: Dog browser - Bs

Create a page that helps people learn about dogs. The page shows four breeds beginning with B. It should use a <table> to show the dogs.

When the page loads, it looks like this:

Opening screen

Figure 1. Opening screen

When the mouse moves over a dog, two things happen:

  • The mouse cursor changes to a hand.
  • The breed’s name shows up.

Mouse over

Figure 2. Mouse over

When the user clicks on a dog, details of the breed show:

Show details after click

Figure 3. Show details after click

All of the text is from Wikipedia.

When the user moves the mouse off the dog that was clicked, the details are hidden. For example, this is what happens if the user moves the mouse from the Bichon Frise to the Basenji:

Mouse moved to another dog

Figure 4. Mouse moved to another dog

Here are the dog images:

Basenji

Bichon Frise

Bloodhound

Borzoi

The following code might save you some typing.

$('#dog_details').text(
  'The Basenji is a breed of hunting dog that was \
   bred from stock originating in central Africa. \
   Most of the major kennel clubs in the English-speaking \
   world place the breed in the Hound Group; \
   more specifically, it may be classified as belonging \
   to the sighthound type.');

$('#dog_details').text(
  'A Bichon Frise (French, meaning "curly white lap dog") \
   is a small breed of dog of the Bichon type. They are \
   popular pets, similar in appearance to, but larger than, \
   the Maltese. They are a non-shedding breed that requires \
   daily grooming. This lack of shedding makes the Bichon \
   Frise a hypoallergenic breed, which is a very good dog \
   for people who have allergies.');

$('#dog_details').text(
  'The Bloodhound (also known as the St. Hubert hound \
   and Sleuth Hound) is a large breed of dog that was \
   bred originally to hunt deer and wild boar, later \
   specifically to track human beings by scent. It is \
   famed for its ability to follow scents hours or \
   even days old over great distances.');
   
$('#dog_details').text(
  'The borzoi is a breed of domestic dog (Canis lupus \
   familiaris) also called the Russian wolfhound and \
   descended from dogs brought to Russia from central \
   Asian countries. It is similar in shape to a greyhound, \
   and is also a member of the sighthound family.');

The \ is JavaScript’s line continuation character. It lets you split a statement across lines. Mainly it’s used to split long strings, to make them easier to read in a code editor, like NetBeans.

Notes:

  • Remember, your page should use a <table> to show the dogs.
  • You can bind both click and hover events to the same element.

Upload your solution to your server, and paste the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Explore

These challenging exercises may use HTML not covered in CoreDogs. Get ready to Google!

Exercise: Sticky headers

Improve your population growth rate table. Make the column headers sticky. As the user scrolls through the page, the column headers (Rank, Country, and Rate) stay in view.

Hint: is there a jQuery plugin you can use?

Upload the solution to your server, and enter the URL.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Download table data

Figure out a way you can help the user put the data in the population growth rate table into Excel, or another spreadsheet program.

Hint: find out what CSV means.

Upload the solution to your server, and enter the URL.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Web pages with links

Where are we?

So far we’ve focused on individual Web pages. You know how to add text and images. You know how to make text and images interact with the user, creating things like photo galleries.

Now we switch our attention to creating links between pages. This is the last piece before we talk about entire Web sites, in the next lesson.

This lesson’s goals

By the end of this lesson, you should:

Let’s get started!

Making links

This page’s goals

By the end of this page, you should:

  • Be able to use the <a> tag to make links.
  • Know the difference between absolute, relative, and root relative links.
  • Be able to make a link open in a new browser tab or window.
  • Be able to create a table of contents for a long page.

Links tie Web pages together. A link appears on a source page. Click it, and the browser shows the destination or target page.

Links are used in two main ways on Web pages. First, they can form navigation bars, also called nav bars. A navigation bar is a group of links that appear together in a block. Here’s a navigation bar:

Horizontal navigation bar

Figure 1. Navigation bar

CSS makes each link look like a tab, but each one is just a regular link. Notice that the “lesson” link looks different from the others. This tells you that the page showing the navigation bar is in the Lessons section of the site.

Navigation bars can be just simple text as well. Here’s part of a navigation bar from Gmail:

Horizontal navigation bar - just text

Figure 2. Horizontal navigation bar – just text

So, the first way that links are used on Web pages is to make navigation bars.

The second way is just as part of the main content of a page. For example, here is a link to CoreDog’s articles list. It’s just a normal part of this paragraph.

Most links on a page are in navigation bars, or part of the content. But links are also used in tables of contents, site maps, and other things. We’ll look at tables of contents and site maps in this lesson.

Example: Dog nutrition

Let’s look at a scenario we’ll use to talk about links. Suppose you start a business around dog nutrition. You create a site at http://dognutrition.bz (available at the time of writing). The site has:

  • Tutorials on dog nutrition, like a page on nutrition for puppies and another on nutrition for older dogs.
  • Articles on more specific topics, like diet supplements for active large dogs.
  • A blog, where you write about new products, and whatever else interests you.
  • A catalog of products your customers can order.

You create the following directory structure:

Directories

Figure 3. Directories

Here’s what goes in each directory:

1 Root of the site - the home page (index.html) is here
2 HTML files for articles
3 HTML files for nutrition basics
4 HTML files for blog entries
5 Files shared across the site
6 HTML files for the products

Figure 4. What is stored in each directory.

Exercise: Puppy Swarm directories

Puppy Swarm wants a Web site. Puppy Swarm is a small company with lots of puppies. It offers the following services:

  • Swarm of joy. Liven up your party with a swarm of happy puppies. Puppy Swarm will bring them to you, take them away, and help you clean up.
  • Micro-swarm of cheer. Cheer up a friend with a visit from two puppies. Puppy Swarm will handle the transport and wrangling.
  • Play swarm. Bring your dogs to our location for hours of fun.
  • Puppy training. Puppy Swarm’s expert puppy wranglers will help you train your puppy.
  • Puppy stuff. Puppy Swarm finds the best products for your puppy. Food, supplements, toys, leashes, crates, ...

Start by creating a set of folders for the Web site.

Directories for Puppy Swarm

Create an index.html file in the services and products directories. Each index.html file should have the name of the site and the name of the site section. Here’s an example:

Services

Create a home page (index.html in the Web root). Here’s an example:

Home page

Create a directory for this project on your server. Upload your files there. You can enter the URL of the site’s home page below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Now, let’s see how to make links.

The <a> tag

Use the <a> tag to create links. Here’s an example:

<a href="/articles/">Articles</a>

It renders like this:

Articles

The tag has two parts to it:

  • The content the user sees.
  • The URL to go to when the user clicks on the content.

The content of the tag – Articles – is what the user sees. It’s between the <a> and the </a>. The href attribute gives the destination – /articles/. This is where the browser goes when the user clicks.

Some links have a complete URL, like http://coredogs.com/lesson/web-page-structure. But most don’t. They have shortened links, like web-page-structure. How does this work?

URLs can be absolute, relative, or root relative.

Absolute URLs

An absolute URL is complete, including a domain name. For example:

<a href="http://dognutrition.bz/basics/puppies.html">Articles</a>

Absolute URLs are used most when referring to someone else’s Web site, not your own. For example:

<a href="http://download.openoffice.org/index.html">Download OpenOffice</a>

On the page Static Web pages, we talked about a server’s default file. When a browser gives a server just a path, like http://site.com/products/, the server knows what directory to look in – products – but not what file to send. So it looks in products for a file with a default name, usually index.html. If it finds the file, it sends that.

So, when a URL includes the default file name, you can omit it. For example, the OpenOffice link could be:

<a href="http://download.openoffice.org/">Download OpenOffice</a>

When the last character of the URL is /, you can leave it out. This is the same as the previous:

<a href="http://download.openoffice.org">Download OpenOffice</a>

Exercise: Link to Wikipedia

Create a file in the root of your Puppy Swarm site. Call it our-puppies.html. Add a link to Wikipedia’s article on puppies (http://en.wikipedia.org/wiki/Puppies). The page might look like this:

Link to Wikipedia

You can enter the URL of your solution below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Relative URLs

These URLs are missing stuff at the beginning, and don’t begin with a /. For example:

<a href="puppies.html">Puppies</a>

This refers to a page in the same directory as the page containing the link. So if the link above was in the page http://dognutrition.bz/basics/index.html, then the browser would look for http://dognutrition.bz/basics/puppies.html.

However, if the link:

<a href="puppies.html">Puppies</a>

was in the page http://dognutrition.bz/products/food/index.html, the browser would look for http://dognutrition.bz/products/food/puppies.html.

The page you link to does not have to be in the same directory as the page containing the link, as long as you specify the path from the page with the link, to the target page.

Here’s the directory structure for dognutrition.bz we saw earlier, with some files added:

Directories

Figure 5. dognutrition.bz directories

Let’s say we’ve updated the puppy nutrition article. Its URL is http://dognutrition.bz/basics/puppies.html (please find it in Figure 5). We want to put a note on the home page, telling users that the article has been updated, with a link to the updated page:

Link to a file in a subdirectory

Figure 6. Link to a file in a subdirectory

We might add this to the home page at http://dognutrition.bz/index.html:

<p>We've updated our page on <a href="basics/puppies.html">puppy nutrition basics</a>. Check it out!</p>

The browser looks for a directory called basics in the current directory, then looks for a file called puppies.html inside that.

Actually, the browser does the same thing it does for image URLs:

  • Take the URL of the referring page (http://dognutrition.bz/index.html).
  • Drop off the file name (that’s index.html, leaving http://dognutrition.bz/).
  • Append the URL from the <a> tag (that’s basics/puppies.html, giving http://dognutrition.bz/basics/puppies.html).

You can make links to pages at higher levels in the directory tree. For example, you might have a link to the home page in an old blog entry.

Link to a file in a parent directory

Figure 7. Link to a file in a parent directory

The code might be:

<p><a href="../../index.html">Home</a></p>

../ means “go up a level.” So the URL is “go up a level (from /blog/archives/ to /blog/), then go up a level (from /blog/ to /), then find index.html.”

You can also navigate from one subdirectory to another. For example, in the page on the basics of puppy nutrition (http://dognutrition.bz/basics/puppies.html) there might be a link to a page in the supplements directory of the products section:

Link to file in another subdirectory

Figure 8. Link to a file in another subdirectory

The code might be:

<p>We recommend <a href="../products/supplements/vita-mite.html">Vita Mite</a></p>

The code is in http://dognutrition.bz/basics/puppies.html. It says, “from the current directory (/basics/), go up a level, then go into the products/ subdirectory, then go into the supplements/ subdirectory, then find the file vita-mite.html.”

When a relative link navigates between subdirectories, it goes up the tree until it find a common parent, then goes down. In this example, the source is http://dognutrition.bz/basics/puppies.html. The destination is http://dognutrition.bz/products/supplements/vita-mite.html. Their common parent is http://dognutrition.bz/; it’s the part of their URLs they have in common.

Here’s another example. Suppose you have a link in the page http://dognutrition.bz/products/food/food1.html to the page http://dognutrition.bz/products/treats/treat1.html (please find both of them in Figure 8). They both have the common parent http://dognutrition.bz/products/, since both pages are under the products/ part of the Web site’s directory tree. So there’s no need for the link to navigate all the way back to the home page. The code might look like this:

<p>And here's a <a href="../treats/treat1.html">tasty treat</a>!</p>

This link is in http://dognutrition.bz/products/food/food1.html. It says “go up a level (from http://dognutrition.bz/products/food/ to http://dognutrition.bz/products/), then go down into treats/, and find the file treats1.html.” This link has the usual pattern: go up to the common parent (products/), and then go down.

So, you can make a link from any HTML page on your site to any other page. Specify the path with ../ and subdirectory names.

Exercise: Links from the home page

On the home page for Puppy Swarm, create a list of links to the index.html files for each of the sections, and to the Our Puppies page. Like this:

List of links

You can put the URL of your solution below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Root relative URLs

You’ve seen absolute URLs and relative URLs. There’s a third category. It’s the root relative URL.

This is an absolute link to a page on your site, but with the domain name missing. Root relative URLs start with /, which means “go to the root of the site and then follow the path to a file.”

Here’s some code:

<p>Read our <a href="/basics/puppies.html">updated puppy nutrition page</a>.</p>

No matter where this link is on your site, it will always point to the same file.

Root relative links have two main uses. First, they’re good for linking from a page deep in your site to a page in another section of the site. You can leave out a lot of ../../../.

Second, they’re particularly useful in creating Web page templates. We’ll talk about those later in the book.

Suppose you’re just getting started with your dog nutrition business at dognutrition.bz. You’ve launched a beta (version for user testing) of the site, but haven’t done any promotion. The day after your site goes up, dognutrition.com becomes available. W00f! You snap it up, and decide to change everything to the new domain.

What if you had used absolute URLs in your links? Like this:

<p>And here's a <a href="http://dognutrition.bz/products/treats/treat1.html">tasty treat</a>!</p>

You would have to find every dognutrition.bz in every link and change it to dognutrition.com. It would be easy to miss one, leaving users with broken links, and maybe costing you business.

Now suppose you want to change the name of the products directory to dog-nutrition-products. Why would you do this? Because your pages might then rank higher in Google. That makes your products easier for people to find and buy, which means more money to support your coffee and chocolate habits.

Again, you have to change the link above. This time, to:

<p>And here's a <a href="http://dognutrition.bz/dog-nutrition-products/treats/treat1.html">tasty treat</a>!</p>

Ack! What an unw00fy thing.

OK, let’s rewind. What if you had used a relative link to start with? Like this:

<p>And here's a <a href="../treats/treat1.html">tasty treat</a>!</p>

You change to dognutrition.com, so you change the link to… Wait, you don’t have to change the link at all! It still works! The link doesn’t have dognutrition.bz in it, so there’s nothing to change. W00f!

What about changing the directory name to dog-nutrition-products? Again, the link is fine the way it is. There’s nothing to change. W00f times 2!

Most of your links should be relative. This makes your site easier to manage. And easy is good!

Use absolute links to refer to pages outside your domain. You don’t have much choice. For example:

<p>You should use <a href="http://www.mozilla.org/firefox/">Firefox</a>, because of its w00fy Weber add-ons. Also try <a href="http://www.apple.com/safari/">Safari</a>, <a href="http://www.opera.com/">Opera</a>, and <a href="http://www.google.com/chrome/">Chrome</a>.</p>

Sometimes you want to create a link to a spot within a page. For example, the puppies.html page in the dog nutrition site might have a section for small breed puppies, like chihuahuas, and another for large breed puppies, like Great Danes.

...
<body>
...
<h2>Small breed puppies</h2>
...
<h2>Large breed puppies</h2>
...
</body>
...

Figure 9. Puppies page

Suppose you were writing a blog entry, and wanted to add a link to the large breed section of puppies.html. First, you would add an id to the destination in puppies.html:

<h1 id="large_breed">Large breed puppies</h1>

In your blog page, add this link:

<p>You can read more about <a href="/basics/puppies.html#large_breed">more about large breed puppies</a>.</p>

The href attribute has a #, followed by the id of the destination in puppies.html.

You can link to sections of the same page. For example, you might put this in puppies.html:

<p>Read more about large breeds <a href="#large_breeds">later on this page</a>.</p>

When there’s nothing in front of the #, your browser will look in the current page, that is, the one it’s showing.

Example: Table of contents

You can use internal links to make a table of contents for a long page. Here’s an example. You can try it.

<h1>Puppy Nutrition</h1>
<p>Contents:</p>
<ul>
  <li><a href="#small_breed_puppies">Small breed puppies</a></li>
  <li><a href="#large_breed_puppies">Large breed puppies</a></li>
</ul>
<p>Lorem ... libero.</p>
<h2 id="small_breed_puppies">Small breed puppies</h2>
<p>Lorem ... libero.</p>
<h2 id="large_breed_puppies">Large breed puppies</h2>
<p>Lorem ... libero.</p>

Figure 8. Table of contents

You’ll notice that the page contains a lot of strange text. This is filler text that won’t distract from the page’s structure. Lorem ipsum text has been the printing industry’s standard dummy text since the 16th century, and Webers have adopted the tradition. You can read more about it, if you want to.

Extra attributes

The <a> tag has other attributes. If you want to open a linked page in a new window, use this:

<a href="www.google.com/" target="_blank">Google</a>

_blank stands for a blank window.

The title attribute pops up a message when the mouse hovers over the link. For example:

<a href="www.google.com/" target="_blank" title="Google search in a new window.">Google</a>

You could also do:

<a href="http://www.google.com/search?q=dog+nutrition" target="_blank" title="Search for 'dog nutrition' in Google. Opens a new window.">Google "dog nutrition"</a>

The ?q=… tells Google to actually run a search. Try it:

Google “dog nutrition”

The URL contains search parameters, as if the user had typed them manually.

So far, all of the links have shown text. But you can add links to images as well, like this:

<a href="/index.html"><img src="/library/home.png" alt="Home"></a>

The browser will jump when the user clicks on the image.

Exercise: Dog pals

Buddy, Honeyface, and Louieeeeee are three dog pals. Create a page for each one. Buddy’s page has a photo of Buddy, and links to Honeyface’s and Louieeeeee’s page. Honeyface’s page has a photo of Buddy, and links to Buddy’s and Louieeeeee’s page. Louieeeeee’s page…, well, you get the idea. All links are on thumbnail images.

Here’s a zoomed out view of Buddy’s page:

Buddy's page

Here are photos you can use.

Buddy thumbnail Buddy

Honeyface thumbnail Honeyface

Louieeeeee thumbnail Louieeeeee

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

If you want to suppress the border on images with links, you can use border: none; in your CSS. Check the page on Styling boundaries for more on CSS and images.

Summary

On this page, you learned:

  • How to use the <a> tag.
  • The difference between absolute, relative, and root relative links.
  • How to make a link open in a new browser tab or window.
  • How to create a table of contents for a long page.

What now?

This lesson is about making links between pages. Put links together with the things you learned in earlier lessons – text, interaction, and images – and you have all you need for a basic Web site.

You’ve seen how to make basic links, but they don’t look great. Let’s fix that.

Styling links

Where are we?

We’ve seen how you make links with the <a> tag. Let’s improve their look.

This page’s goals

By the end of this page, you should:

  • Know what the <a> tag’s pseudo-classes are.
  • Be able to use the pseudo-classes to create link effects.

Review: Basic text styling

You already know how to do basic text styling. For example, you might have style rules like this:


body { font-family: Verdana, Helvetica, sans-serif;
}
h1 { font-size: 24px; color: #660000; font-weight: bold;
}

Figure 1. Styling a heading

This looks like:

Rendered heading

Figure 2. Rendered heading

The first rule changes the font family of everything inside the <body> – and that’s everything on the page. The second rule changes all <h1> tags to 24 pixels high, dark red, and bold.

Here’s a class and an id:

...
.warning {
  border: 1px red solid;
  padding: 5px;
  color: red;
  font-weight: bold;
}
#truth {
  color: #006600;
  font-size: 20px;
  font-style: italic;
}
...
<p>This is a normal paragraph.</p>
<p class="warning">This is a warning.</p>
<p id="truth">Dogs are great!</p>
...

Figure 3. class and id

It looks like:

Rendered class and id

Figure 4. Rendered class and id

The rule in lines 2 to 7 creates a class that can be applied to several tags. Line 15 shows how to use it in HTML, with the class attribute.

Lines 8 to 12 create a rule for a specific element on the page, the one with the id of truth. Line 16 shows how an element is given an id. Only one element on the page can have that id.

You can see this in action.

The same rules apply to links. You can change the typeface, weight, color, and so on. For example:

...
a {
  color: #600000;
  font-weight: bold;
}
...
<p>Please see my <a href="/projects/index.html">projects</a> page.</p>
...

Figure 5. Simple link styling

It will look like:

Rendered link

Figure 6. Rendered link

A warning, though. Keep the links looking like links. You could do this:

a {
  color: #600000;
  font-weight: bold;
  text-decoration: none; /* Evil! */
}

Figure 7. Evil link styling

Line 4 removes the underlining. It would look like this:

Link, link, where is the link?

Figure 8. Link, link, where is the link?

People are used to seeing underlines. That’s how they know something is a link. You can get away with changing the font color from the default blue to something that better suits your site’s color scheme. But if you change the link color, users might not know a link when they see one.

The exception to this is in a navigation bar. The visual context tells users to expect links, even if they aren’t underlined.

Pseudo-classes

Move the mouse cursor over the this link (no need to click):

Learn about making links.

Notice how the text changes when the mouse cursor goes over it.

This is done with pseudo-classes. Pseudo-classes select elements based on some aspect of them. Here’s how the link you just saw was done:

<style type="text/css">
  a.sample1:hover {
    font-weight: bold;
    color: orange;}
</style>

<blockquote>
Learn about <a class="sample1" href="lesson/making-html-links">making links</a>.</blockquote>

Figure 9. Pseudo-class

The pseudo-class is the :hover in line 2. When the mouse is on a link with the class sample1, the text is made bold.

If I’d wanted to change all of the links on the page, I could have done this:

a:hover {font-weight: bold;}

Figure 10. Pseudo-class affecting all links

But I didn’t want to change all of the links.

Browsers use four pseudo-classes for links.

Pseudo-class Browsers use it to show...
:link Link that has not been visited
:visited Link that has been visited
:hover Mouse is over the link
:active Mouse is clicking the link

Figure 11. Pseudo-classes for links

What is the difference between link and visited? The difference is whether the user has visited the target of the link recently. Suppose page begin.html has a link to target.html, like this:

<a href="target.html">See the target</a>

When showing this link, the browser will apply the :link pseudo-class when the user has not visited the target of the link recently. The default styling is usually blue text:

Default styling for <code>:link</code>

Figure 12. Default styling for :link

However, the browser will apply the :visited pseudo-class when the user has visited the target of the link recently. The default styling is usually purple text:

Default styling for <code>:visited</code>

Figure 13. Default styling for :visited

:hover is the most used. The other pseudo-classes are used less frequently.

Exercise: Styling links

Create a page with light gray text on a black background. Links normally look like this:

Normal link

When the mouse cursor is on the links, invert the colors. That is, black text on a light gray background:

Hover link

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

The hover pseudo class applies not just to links, but to other things as well. Here’s an example:

...
p {
  margin: 10px;
  padding: 10px;
  background-color: #7534AA;
  color: white;
}
p:hover {
  background-color: #B484DA;
}
...
<p>W00f!</p>
...

Figure 14. Hovering over a <p>

The <p> will look like this normally:

Hoverless

Figure 15. Hoverless

The <p> will change to this on hovering.

Hovery

Figure 16. Hovery

Notice that when the mouse is over the <p>, the browser applies both the p { } and p:hover { } rules. The background color in the p:hover { } rule replaces the background color in the p { } rule.

You can try it yourself.

Summary

On this page, you learned what the <a> tag’s pseudo-classes are, and how to use them to create link effects. The :hover tag is the most frequently used. Don’t remove underlining from links.

What now?

Let’s see how you can use styled links to create cool navigation bars.

Vertical navigation bars

Where are we?

This lesson is about linking pages together. You know how to make basic links, and style them. Let’s put this together to create a vertical navigation bar.

Once you’ve finished this lesson about links, you’ll have all you need for a basic Web site.

This page’s goals

By the end of this page, you should be able to:

  • Create vertical nav bars with text.
  • Position vertical nav bars.
  • Create vertical nav bars with images.
  • Create image nav bars with hover effects.

Vertical nav bars with text

A navigation bar (nav bar) is a set of links shown together as a visual block. Each link is sometimes called a button.

The simplest nav bars are just text links. Here’s an example:

<p>
  <a href="dummy.html" title="Back to the home page">Home</a>
</p>
<p>
  <a href="dummy.html" title="The basics of dog nutrition">The basics</a>
</p>
<p>
  <a href="dummy.html" title="Articles on dog nutrition">Articles</a>
</p>
<p>
  <a href="dummy.html" title="Products we recommend">Products</a>
</p>
<p>
  <a href="dummy.html" title="Our bloggy nutrition updates">Blog</a>
</p>

Figure 1. Nav bar with paragraphs

You can try the page. (The links only go to a dummy page, as you can see from the code.)

It doesn’t look good. There’s too much space between the links, for starters.

We could style the paragraphs, or use <br> instead of <p></p>. But there’s a better way.

Unordered lists are convenient for vertical nav bars. Here’s the same menu as a list.

<ul>
  <li>
    <a href="dummy.html" title="Back to the home page">Home</a>
  </li>
  <li>
    <a href="dummy.html" title="The basics of dog nutrition">The basics</a>
  </li>
  <li>
    <a href="dummy.html" title="Articles on dog nutrition">Articles</a>
  </li>
  <li>
    <a href="dummy.html" title="Products we recommend">Products</a>
  </li>
  <li>
    <a href="dummy.html" title="Our bloggy nutrition updates">Blog</a>
  </li>
</ul>

Figure 2. Nav bar as a list

You can try the page. It will look like this:

Rendered unstyled list

Figure 3. Rendered unstyled list

Exercise: Unstyled vertical navigation

Get started with a vertical nav bar for Puppy Swarm. It should look like this:

Vertical nav bar

You can just link each one to a dummy page.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Suppose we wanted the menu to look like this:

Rendered styled list

Figure 4. Rendered styled list

We would need to apply styles to the entire menu (like the border), as well as to the individual menu elements (like removing the underline). The

<ul>
<li></li>
</ul>

structure suits this. We can style the entire menu by styling the <ul>. We can style the individual links by styling the <li>s. There are other ways to do things, but many Webers find unordered lists convenient for vertical menus.

Let’s put Figures 3 and 4 side-by-side, and identify the differences between them:

Differences

Figure 5. Differences

The page background color is yellow. The menu has a dotted blue line around it, a blue background, and gaps between the menu and the top and left. The links have some font styling, no dot, and gaps between them and the menu borders.

Here’s some CSS that will do the job:

body {
  font-family: Verdana,  Helvetica, sans-serif;
  font-size: 14px;
  background: #FFFFEE;
}
.vertical_menu {
  border: 1px dotted blue;
  background-color: #EEFFFF;
  margin: 5px;
  padding: 5px;
}
.vertical_menu li {
  list-style: none;
  margin: 5px;
}
.vertical_menu li a {
  text-decoration: none;
  color: black;
}
.vertical_menu li a:hover {
  text-decoration: underline;
}

Figure 6. Nav bar CSS

Let’s go over it.

Lines 1 to 5 set the font face and size, and background color for the entire page. Unless overridden, everything on the page will look like this.

Lines 6 to 10 style the menu block. They add the border and background color. Lines 9 and 10 add spacing around the menu, and between the menu’s border and its contents.

Lines 12 to 14 style the <li>s. Note the selector: .vertical_menu li. This applies to <li> elements inside elements with the class vertical_menu. The rule doesn’t apply to other <li> elements on the page. list-style: none; removes the dot that usually appears to the left of list elements.

The rule in lines 16 to 19 applies to <a>s that are inside <li>s that are inside elements with the class vertical_menu. It removes the underlining, and sets the text color to black, rather than the default link color (usually blue).

The rule in lines 20 to 22 says what happens when the mouse hovers over a link in a menu. It gets underlined.

You can try the result. Much of w00f!

Exercise: Styled vertical navigation

Create a styled vertical nav bar for Puppy Swarm. It should look like this:

Vertical nav bar

The color code for the purple is 7534AA.

When the mouse cursor moves over a link, it changes to a lighter purple. Use the color code B484DA.

Hint: remember that an <li> can use the hover pseudo-class.

Upload your solution to your server, and put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Positioning vertical nav bars

Vertical nav bars usually appear at the left or right of Web pages. They also are just wide enough to show their links.

Suppose we want this:

Menu on the left

Figure 7. Menu on the left

The menu is to the left of the content, and is narrow. Easy! Just make a few changes to Figure 6.

.vertical_menu {
  float: left;
  width: 90px;
...
}
...
<h1>Dog Land</h1>
<ul class="vertical_menu">
...
</ul>
<p>Lorem ipsum dolor sit... 

Figure 8. Floaty float

You can try it.

Line 2 is the key. It changes the positioning of the element.

You give HTML to a browser, and it renders it. Normally, the browser makes content flow down the page from top to bottom, in the order it appears in the HTML. So if you have:

<p id="para1">I am evil!</p>
<p id="para2">I like donuts!</p>

The user will see para1 on the screen, and below that, para2, like this:

Evil donuts

Figure 9. Evil donuts

This is called static positioning, and is the browser default. The order of each element on the page matches its order in the HTML.

If I remove the float line from Figure 8, this is what I get:

Floatless

Figure 10. Floatless

You can try it. You’ll see the usual static flow.

float – and other positioning rules – let you change that. float takes an element out of flow, draws it, and then resumes drawing the other elements around it. float: left; moves an element to the left of the browser window. float: right; moves an element to the right.

Put the earlier figures one under the other, and you can easily see the difference:

Floatless

Menu on the left

Figure 11. The menus

In the normal flow, the menu appears between the header (Dog Land) and the main content (Lorem ipsum). When the menu is floated, it gets “pinned” to the edge of the window. The element below the menu moves up, and wraps around it.

Time for a w00f.

W00f!

Exercise: Floated styled vertical navigation

Float the Puppy Swarm nav bar:

Floated nav bar

Upload you solution to your server, and enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Lots o’ content

But there’s a problem. Suppose I add lots of content to the page in Figure 8. It would look like this:

Lots of content

Figure 12. Lots of content

The content wraps around the nav bar. Sometimes this is what you want. But you might want this:

Content does not wrap

Figure 13. Content does not wrap

In Figure 13, the nav bar takes its own column on the page.

How to do this? The easiest way is to wrap the main content in its own <div>, and give the <div> a margin.

.vertical_menu {
  float: left;
  width: 90px;
...
}
...
#main_content {
  margin-left: 120px;
}
...
<h1>Dog Land</h1>
<ul class="vertical_menu">
...
</ul>
<div id="main_content">
  <p>Lorem ipsum dolor sit... 
  ...
</div>

Figure 14. Floaty float nav bar in its own column

This pushes the content to the left, relative to its container. The <div>’s container is the <body>. So each element in the <div> (e.g., each <p> in the <div>) has the same left indent, regardless of whether there is nav bar stuff to the left of it or not. You can try it.

Exercise: Fixing your vertical nav bar

You created a vertical nav bar in the previous exercise. Copy your solution to another page. Then adds lots of content to it. Verify that the content wraps around the nav bar, like this:

Wrappy content

Fix it so that the main content of the page does not wrap around the nav bar. It should look something like this:

Wrapless content

Upload your solution to your server. Enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Vertical nav bars with images

Sometimes you want to use images instead of text. Let’s make a menu like this:

Vertical nav bar with images

Figure 15. Vertical nav bar with images

Once you understand how to make a text nav bar, making one with images is fairly easy.

First, you need to get the images for the buttons. Then you can put them into a menu.

Where to get button images?

You can make them your yourself, or you can have a program generate them for you. Let’s use the latter option.

ButtonGenerator.Com is a useful site. You select an image, enter some text, and it will create some nice buttons. That’s what I did to make the images in Figure 15.

The HTML

As a reminder, here’s a link from a text nav bar:

<a href="dummy.html" title="Back to the home page">Home</a>

Replace the text with an image:

<a href="dummy.html" title="Back to the home page"><img src="button-images/home.png" alt="Back to the home page"></a>

Don’t forget the alt, for visually impaired users with screen reading software. Also, Google uses the alt attribute when it lists your image in its search engine. Google’s search software can’t figure out the meaning of picture from their contents. Not even Google’s computers are that smart. Yet. So instead, Google’s software uses the alt text to decide what the image is showing.

Images that are in links have a border by default:

Button with an evil border

Figure 16. Button with a border

Use border:none; in your CSS to suppress the border.

Here’s the code so far:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Vertical nav bar</title>
    <style type="text/css">
      body {
        font-family: Verdana,  Helvetica, sans-serif;
        font-size: 14px;
        background-color: #FDF4DE; 
      }
      .vertical_menu {
        float: left;
        width: 145px;
        background-color: #F7DB94;
        padding: 5px;
        margin: 5px;
      }
      .vertical_menu li {
        list-style: none;
        margin: 5px;
      }
      .vertical_menu li a img {
        border: none;
      }
    </style>
  </head>
  <body>
    <ul class="vertical_menu">
      <li>
        <a href="dummy.html" title="Back to the home page">
          <img src="button-images/home.png" alt="Back to the home page">
        </a>
      </li>
      <li>
        <a href="dummy.html" title="The basics of dog nutrition">
          <img src="button-images/basics.png" alt="The basics of dog nutrition">
        </a>
      </li>
      <li>
        <a href="dummy.html" title="Articles on dog nutrition">
          <img src="button-images/articles.png" alt="Articles on dog nutrition">
        </a>
      </li>
      <li>
        <a href="dummy.html" title="Products we recommend">
          <img src="button-images/products.png" alt="Products we recommend">
        </a>
      </li>
      <li>
        <a href="dummy.html" title="Our bloggy nutrition updates">
          <img src="button-images/blog.png" alt="Our bloggy nutrition updates">
        </a>
      </li>
    </ul>
  </body>
</html>

Figure 17. HTML for vertical nav bar with images

As you can see from lines 32, 37, 42, and so on, I put all the button images in their own directory, called button-images. Each image is a PNG file, named after the text on the button. So articles.png has the text “Article.” Neither browser nor server care what I call the file. But it’s easier to keep things straight if I name them consistently.

You can try out the vertical nav bar with images.

Adding hover effects

The last thing we’ll do is add a hover effect, so that when the user puts the mouse over a button, the image changes.

Here’s what we want to achieve. Move your mouse over the image below, and off again.

Home

Figure 18. Hover effect

Notice how an arrow appears when the mouse moves over the button.

More buttons

We need two versions of the button image:

  • Without the arrow – the normal button state.
  • With the arrow – shown when the mouse hovers on the button.

I had already made the first one:

Home button, no arrow

I called it home.png, as you can see on line 32 in Figure 17.

I went back to ButtonGenerator.Com to make the second image. ButtonGenerator lets you add an icon to a button. I chose the arrow. Here’s what I created:

Home button, with arrow

I called this one home-over.png.

I made an X-over.png image for every button: basics-over.png, etc. I put them in the same directory as the other button images.

How to get the X-over.png images to show? There are many ways to do it. Let’s see one way using jQuery.

jQuery over and out

Here’s what I want to do for the Home button:

  • When the mouse goes over the image, show home-over.png.

Home button, with arrow home-over.png

  • When the mouse leaves the image, show home.png.

Home button, without arrow home.png

We need to attach code to the Home button. So let’s start by giving the button an id so we can refer to it:

<a href="dummy.html" title="Back to the home page">
  <img id="home_button" src="button-images/home.png" alt="Back to the home page">
</a>

Figure 19. Adding an id

I added an id of home_button.

Now I can add an event to the img. Remember that an event is something that happens to an element. For example, click() happens when the user clicks on an element with the mouse.

jQuery has a hover() event that’s just right for the job. hover() actually captures two events. Here’s how it’s used:

$(target element).hover(
  function(){
    Code to run when the mouse goes over the target element.
  },
  function(){
    Code to run when the mouse leaves the target element.
  }
);

Figure 20. hover() event

Line 1 tells jQuery which element is having the event attached to it. The code in the first function (lines 2 to 4) runs when the mouse goes over the element. You can put as many lines of code as you want. The code in the second function (lines 5 to 7) runs when the mouse leaves the element. Again, you can put as many lines of code as you want.

I named the button home_button. So the code should do this:

For home_button:
  Over: Make home_button show home-over.png.
  Leave: Make home_button show home.png.

Figure 21. hover() event pseudocode

What now? Well, I know the name of the image that should have the event. So let me change Figure 20 to:

$("#home_button").hover(
  function(){
    Make home_button show home-over.png.
  },
  function(){
    Make home_button show home.png.
  }
);

Figure 22. Improved hover() event

Remember that $("#home_button") refers to the element with the id of home_button. Don’t forget the #.

But how can I make home_button show home-over.png? Let’s look at the HTML again – it’ll give us a clue. The HTML is:

<a href="dummy.html" title="Back to the home page">
  <img id="home_button" src="button-images/home.png" alt="Back to the home page">
</a>

Figure 19 (again). Adding an id

Line 2 shows how you tell an <img> what image to show: you set the src attribute to the path to the image file. If I changed the src attribute, <img> will show a different image.

I can change any attribute of any element with the attr() function. I tell it what attribute I want to change, and what the new value is, and jQuery will change the attribute.

For example, this:

$("#thing").attr("class", "evil");

would set the class attribute of the element thing to evil. This is a useful technique for changing the look of something on the fly.

This:

$("#tomato").attr("title", "This is a fruit");

would change the title attribute of the element tomato.

Since src is just another attribute, we could do this:

$("#home_button").attr("src", "home-over.png");

Actually, this won’t quite work, because I put the image in a subdirectory. The code should be:

$("#home_button").attr("src", "button-images/home-over.png");

This is what I end up with:

$('#home_button').hover(
  function(){
    //Run on mouse over.
    $('#home_button').attr('src', 'button-images/home-over.png');
  },
  function(){
    //Run on mouse out.
    $('#home_button').attr('src', 'button-images/home.png');
  }
);

Figure 23. hover() event code

Events are usually assigned in the page’s ready() event. That is, after the page is loaded (i.e., ready), that’s when the hover() code should be bound to home_button. So the script section of the page will be:

<script type="text/javascript">
  $(document).ready(function() {
    $('#home_button').hover(
      function(){
        //Run on mouse over.
        $('#home_button').attr('src', 'button-images/home-over.png');
      },
      function(){
        //Run on mouse out.
        $('#home_button').attr('src', 'button-images/home.png');
      }
    );
  });
</script>

Figure 24. hover() event – even better!

What about the rest of the buttons? Create the with-arrow images, and change the code.

$('#home_button').hover(
  function(){
    //Run on mouse over.
    $('#home_button').attr('src', 'button-images/home-over.png');
  },
  function(){
    //Run on mouse out.
    $('#home_button').attr('src', 'button-images/home.png');
  }
);
$('#basics_button').hover(
  function(){
    //Run on mouse over.
    $('#basics_button').attr('src', 'button-images/basics-over.png');
  },
  function(){
    //Run on mouse out.
    $('#basics_button').attr('src', 'button-images/basics.png');
  }
);
...
<li>
  <a href="dummy.html" title="Back to the home page">
    <img id="home_button" src="button-images/home.png" alt="Back to the home page">
  </a>
</li>
<li>
  <a href="dummy.html" title="The basics of dog nutrition">
    <img id="basics_button" src="button-images/basics.png" alt="The basics of dog nutrition">
  </a>
</li>

Figure 25. More hover() code

You can try the final vertical nav bar with images.

W00f!

Exercise: Vertical nav bar with images

Create a vertical nav bar for Puppy Swarm. It should look like this:

Vertical nav bar

When the user moves the mouse over a button, the image should change. Make the font larger, change color, whatever you like.

You can use these images if you want.

Home Home over

Services Services over

Products Products over

Puppies Puppies over

Contact Contact over

Upload your solution to your server. Enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

On this page, you learned how to:

  • Create vertical nav bars with text.
  • Position vertical nav bars.
  • Create vertical nav bars with images.
  • Create image nav bars with hover effects.

What now?

Now let’s look at horizontal nav bars. With all the work we did on the vertical nav bars, the horizontal ones will be easy.

Horizontal navigation bars

Where are we?

This lesson is about linking pages together. You know how to make basic links and style them. You just learned how to create a vertical navigation bar.

This page’s goals

This page is about horizontal navigation bars. By the end of this page, you should be able to:

  • Create horizontal nav bars with text.
  • Position horizontal nav bars.
  • Create horizontal nav bars with images and hover effects.

Horizontal nav bars with text

Let’s create a navigation bar that looks like this:

Horizontal nav bar with text

Figure 1. Horizontal nav bar with text

It’s like the vertical one we made on the last page. Remember, it looked like this:

Vertical nav bar with text

Figure 2. Vertical nav bar with text

To turn the vertical menu into a horizontal one, we only need to add one CSS property. Really! Here’s the code for the horizontal menu.

<!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>Nav bar</title>
    <style type="text/css">
      body {
        font-family: Verdana,  Helvetica, sans-serif;
        font-size: 14px;
        background: #FFFFEE;
      }
      .horizontal_menu {
        border: 1px dotted blue;
        background-color: #EEFFFF;
        padding: 5px;
        margin: 5px;
      }
      .horizontal_menu li {
        display: inline;
        list-style: none;
        margin: 5px;
      }
      .horizontal_menu li a {
        text-decoration: none;
        color: black;
      }
      .horizontal_menu li a:hover {
        text-decoration: underline;
      }
    </style>
  </head>
  <body>
    <ul class="horizontal_menu">
      <li>
        <a href="dummy.html" title="Back to the home page">Home</a>
      </li>
      <li>
        <a href="dummy.html" title="The basics of dog nutrition">The basics</a>
      </li>
      <li>
        <a href="dummy.html" title="Articles on dog nutrition">Articles</a>
      </li>
      <li>
        <a href="dummy.html" title="Products we recommend">Products</a>
      </li>
      <li>
        <a href="dummy.html" title="Our bloggy nutrition updates">Blog</a>
      </li>
    </ul>
  </body>
</html>

Figure 3. HTML and CSS for horizontal nav bar with text

You can try the horizontal text nav bar. It’s quite w00fy.

Line 19 is new. (OK, I also changed the class vertical_menu to horizontal_menu, but that’s not really new.)

Earlier, in the page Simple font tags, I explained the difference between block tags and inline tags. Here’s some HTML:

<p>I <em>really</em> love dogs.</p>

It renders likes this (though smaller and without the lines):

Inline and block

Figure 4. Inline and block

The <p> tag is a block tag. It creates a square block on the screen, with white space on all sides.

The <em> tag is an inline tag. It’s turned on inside a block tag, and keeps running until it gets turned off.

An inline tag might not create a rectangular area. This code:

<p>I <em>really really really really really really </em> love dogs.</p>

It might look like this, in a browser that’s zoomed in and put in a small window:

Inline not always a rectangle

Figure 5. Inline not always a rectangle

You can’t draw a rectangle around the italicized text without including other stuff. But for a block tag, you can draw a simple rectangle that bounds the block content.

The bottom line: block tags create a rectangular area for themselves. Inline tags don’t. They’ll keep things on the same line, if they can.

<li> is normally a block tag. That is, the browser puts it in a rectangle of its own. Take this code:

...
li {
  border: 1px red dotted;
}
...
<ul>
  <li>
    The first thing.
  </li>
  <li>
    The second thing.
  </li>
</ul>
....

Figure 6. <li> as block tag

It renders as:

li as block tag - rendered

Figure 7. <li> as block tag – rendered

But if I add one line, making the style:

li {
  border: 1px red dotted;
  display: inline;
}

Figure 8. Display inline

This is what I get:

li as inline tag - rendered

Figure 9. <li> as inline tag – rendered

Each <li> sits in line with the others.

That’s how we get a horizontal text nav bar.

Positioning horizontal nav bars

You usually put horizontal nav bars at the top or bottom of a page. They don’t need any special positioning. Just include them in the HTML, and they naturally fall into place.

Suppose we wanted this:

Horizontal nav bar

Figure 10. Horizontal nav bar

Here’s some code:

...
<body>
  <h1>Dog Land</h1>
  <ul class="horizontal_menu">
    <li>
      <a href="dummy.html" title="Back to the home page">Home</a>
    </li>
...
</ul>
<p>Lorem ipsum dolor sit amet, consectetur 
...

Figure 11. Code for horizontal nav bar

There’s the heading (line 3), then the menu (lines 4 to 9), then the page content. This creates the display in Figure 10. No need to use the CSS float property, as we did with the vertical nav bars. You can try a page with a horizontal text nav bar.

Exercise: Styled horizontal navigation bar

Create a nav bar for Puppy Swarm that looks like this when added to a page (I shrank the image to make it fit):

Nav bar

The color code for the purple is 7534AA.

When the mouse cursor moves over a link, it changes to a lighter purple. Use the color code B484DA.

Upload your solution to your server. Enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Image nav bars with rollover effects

On the previous page, we created a vertical nav bar with an image rollover effect. You can try the vertical nav bar to remind yourself how it acted.

A few changes to the CSS convert it into a horizontal nav bar. Here is the code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Horizontal nav bar</title>
    <style type="text/css">
      body {
        font-family: Verdana,  Helvetica, sans-serif;
        font-size: 14px;
        background-color: #FDF4DE; 
      }
      .horizontal_menu {
        background-color: #F7DB94;
        padding: 5px;
        margin: 5px;
      }
      .horizontal_menu li {
        display: inline;
        list-style: none;
        margin: 5px;
      }
      .horizontal_menu li a img {
        border: none;
      }
    </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() {
        $('#home_button').hover(
          function(){
            //Run on mouse over.
            $('#home_button').attr('src', 'button-images/home-over.png');
          },
          function(){
            //Run on mouse out.
            $('#home_button').attr('src', 'button-images/home.png');
          }
        );
        $('#basics_button').hover(
          function(){
            //Run on mouse over.
            $('#basics_button').attr('src', 'button-images/basics-over.png');
          },
          function(){
            //Run on mouse out.
            $('#basics_button').attr('src', 'button-images/basics.png');
          }
        );
        $('#articles_button').hover(
          function(){
            //Run on mouse over.
            $('#articles_button').attr('src', 'button-images/articles-over.png');
          },
          function(){
            //Run on mouse out.
            $('#articles_button').attr('src', 'button-images/articles.png');
          }
        );
        $('#products_button').hover(
          function(){
            //Run on mouse over.
            $('#products_button').attr('src', 'button-images/products-over.png');
          },
          function(){
            //Run on mouse out.
            $('#products_button').attr('src', 'button-images/products.png');
          }
        );
        $('#blog_button').hover(
          function(){
            //Run on mouse over.
            $('#blog_button').attr('src', 'button-images/blog-over.png');
          },
          function(){
            //Run on mouse out.
            $('#blog_button').attr('src', 'button-images/blog.png');
          }
        );
      });
    </script>
  </head>
  <body>
    <ul class="horizontal_menu">
      <li>
        <a href="dummy.html" title="Back to the home page">
          <img id="home_button" src="button-images/home.png" alt="Back to the home page">
        </a>
      </li>
      <li>
        <a href="dummy.html" title="The basics of dog nutrition">
          <img id="basics_button" src="button-images/basics.png" alt="The basics of dog nutrition">
        </a>
      </li>
      <li>
        <a href="dummy.html" title="Articles on dog nutrition">
          <img id="articles_button" src="button-images/articles.png" alt="Articles on dog nutrition">
        </a>
      </li>
      <li>
        <a href="dummy.html" title="Products we recommend">
          <img id="products_button" src="button-images/products.png" alt="Products we recommend">
        </a>
      </li>
      <li>
        <a href="dummy.html" title="Our bloggy nutrition updates">
          <img id="blog_button" src="button-images/blog.png" alt="Our bloggy nutrition updates">
        </a>
      </li>
    </ul>
  </body>
</html>

Figure 12. Horizontal nav bar with image rollover

I added line 18, to make the <li>s line up horizontally.

The vertical menu had this rule, applied to the <ul>:

...
.vertical_menu {
  float: left;
  width: 145px;
  background-color: #F7DB94;
  padding: 5px;
  margin: 5px;
}
...
<ul class="vertical_menu">
...

Figure 13. Vertical code reminder

Lines 3 and 4 are gone from the horizontal version. I just let the content flow naturally. There was no need to float anything.

W00f!

The Sneaky Underline of @DOOM@

Check out this page. It has this problem:

Extra underline

Figure 14. Extra underline

Hey! Where did the little line come from?

Let’s look at the code:

<ul class="horizontal_menu">
  <li>
    <a href="dummy.html">
      <img src="amd_xp.png" alt="AMD">
    </a>
  </li>
  ...
</ul>

Figure 15. Code that makes the extra line

The problem is in lines 3 to 5. This would eliminate the extra line:

<ul class="horizontal_menu">
  <li>
    <a href="dummy.html"><img src="amd_xp.png" alt="AMD"></a>
  </li>
  ...
</ul>

Figure 16. The extra line – gone!

It’s the white space between <a> and </a> that causes the problem. This is one time that white space in HTML code matters.

Having the look of the page depend on formatting of the code…, well, it’s a Bad Thing. We can use CSS to make the problem go away:

.horizontal_menu li a {
  text-decoration: none;
} 
...
<ul class="horizontal_menu">
  <li>
    <a href="dummy.html">
      <img src="amd_xp.png" alt="AMD">
    </a>
  </li>
  ...
</ul>

Figure 17. Using CSS to kill the extra line

The CSS rule removes the underline that <a> normally has.

Check it out. Here’s what it looks like:

No problem

Figure 18. No problem

Exercise: Horizontal navigation bar with images

Create a horizontal navigation bar with images and a hover effect for Puppy Swarm. Your page should look like this (I shrank the image to fit):

Nav bar

When the user moves the mouse over a button, the image should change. Make the font larger, change color, whatever you like.

You can use these images if you want.

Home Home over

Services Services over

Products Products over

Puppies Puppies over

Contact Contact over

Upload your solution to your server. Enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

On this page, you learned how to:

  • Create horizontal nav bars with text.
  • Position horizontal nav bars.
  • Create horizontal nav bars with images and hover effects.

What now?

Put your skills to work on your own site.

eMe: Make a nav bar

Where are we?

You know how to make nav bars. Make one for your eMe.

eMe nav bar

Make a nav bar that will jump to different parts of your eMe. You’ve made these things so far:

You could make a nav bar with links to each of these pages.

Exercise: A nav bar for your eMe

Make a nav bar that will jump to different parts of your eMe.

Upload it to your server. Enter the URL

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

What now?

You’ve learned a lot in this lesson! Make links, style them, and make fancy nav bars. Add this to the stuff you learned in the previous lesson – text, interaction, and images – and you know enough to make a complete Web site.

Let’s add one more thing that’s common on real Web sites: a site map.

Site maps

Where are we?

This lesson is about linking pages together. You know how to make basic links and style them. You know how to make w00fy navigation bars.

This page’s goals

This page is about site maps. By the end of this page, you should:

  • Know what a site map is for.
  • Be able to create a site map from nested lists.

What is a site map is for?

A site map is a Web page that summarizes an entire Web site, or a big chunk of a Web site. Here’s an example, zoomed out so you can see most of it.

Traditional site map

Figure 1. Traditional site map

There’s a link for each main section of the site. Links to pages in that section are indented under it.

Some maps are horizontal, like this:

Mozilla site map

Figure 2. Mozilla site map

There’s not as much room for text with these maps, but they take up less screen space. Some maps like this are added to the bottom of every page. You can see more examples on the Web Designer Wall.

Site maps have three goals:

  • They let users get a quick overview of a site’s contents.
  • They let experienced users quickly jump to pages deep in the site.
  • They help search engines find all of the content on the site.

Let’s see how to make a traditional, vertical site map.

Site maps as nested lists

An easy way to make a site map is with nested lists. Suppose we wanted to make a site map like this for the dog nutrition site.

Simple site map

Figure 3. Simple site map

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>Site Map</title>
    <style type="text/css">
      body {
        font-family: Verdana, Helvetica, sans-serif;
        font-size: 14px;
        background-color: #FFFFCC;
      }
      #site_map li {
        list-style: none;
        margin: 10px;
      }
    </style>
  </head>
  <body>
    <h1>Site Map</h1>
    <ul id="site_map">
      <li>
        <a href="dummy.html" title="The basics of dog nutrition">The basics</a>
      </li>
      <ul>
        <li>
          <a href="dummy.html" title="Help your puppy grow">Puppy nutrition</a>
        </li>
        <li>
          <a href="dummy.html" title="Keep your older dog healthy">Nutrition for older dogs</a>
        </li>
        <li>
          <a href="dummy.html" title="Food can help with chronic illness">Nutrition when your dog is ill</a>
        </li>
      </ul>
      <li>
          <a href="dummy.html" title="Articles on dog nutrition">Articles</a>
      </li>
      <li>
          <a href="dummy.html" title="Our bloggy nutrition updates">Blogs</a>
      </li>
      <ul>
        <li>
          <a href="dummy.html" title="What's on our minds right now">Latest entry</a>
        </li>
        <li>
          <a href="dummy.html" title="Advice from the past">Archive</a>
        </li>
      </ul>
      <li>
        <a href="dummy.html" title="Products we recommend">Products</a>
      </li>
      <ul>
        <li>
          <a href="dummy.html" title="The foundation of good nutrition">Food</a>
        </li>
        <li>
          <a href="dummy.html" title="Healthy rewards">Treats</a>
        </li>
        <li>
          <a href="dummy.html" title="For everyday vitality,and special needs">Supplements</a>
        </li>
        <li>
          <a href="dummy.html" title="Containers, recipes, gifts, ...">Other</a>
        </li>
      </ul>
    </ul>
  </body>
</html>

Figure 4. Code for a simple site map

There are nested lists, that is, there are lists inside lists. This works because browsers indent <ul>s relative to their containers.

To understand this, have a look at this code snippet:

...
ul {
  border: 1px red dashed;
}
...
<p>Some content</p>
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <ul>
    <li>Item 3</li>
    <li>Item 4</li>
  </ul>
  <li>Item 5</li>
</ul>
<p>Some content</p>
...

Figure 5. Indenting and containership

This creates:

Rendered page

Figure 6. Rendered page

You can try the page.

The style rule on lines 2 to 4 draws a border around the <ul>s, so they stand out.

The first <ul> on line 7 is contained inside the <body>. Another way to say it is that the <ul> is a direct child of, or direct descendant of, the <body>. So the browser indents its <li>s relative to the <body>.

The second <ul> on line 10 is contained in the first <ul>. So its <li>s are indented relative to the first <ul>.

This container effect makes it easy to create progressive indents. Just put one list inside another.

CC
CC

A question.

Kieran
Kieran

Go ahead.

CC
CC

I noticed that the source code in Figure 5 is indented. It sort of matches the indenting that the user sees, in Figure 6. Can you indent stuff on a Web page by indenting the HTML?

Kieran
Kieran

No, you can’t. Let me explain.

The way the HTML source code is indented in Figure 5 does not affect what the browser draws on the screen. Here’s the same code, with the indenting messed up.

<p>Some content</p>   <ul><li>
Item 1</li>
<li>
Item 
2</li>
<ul>  <li>Item 3
</li><li>Item 4
</li>
        </ul>
   <li>Item 
5</li>
  </ul><p>Some content</p>

Figure 7. Source code indenting messed up

The browser shows exactly the same thing as it did before. You can try it yourself.

So the indenting the user sees, that is, this…

Rendered page

Figure 6 (again). Rendered page

...depends on containership and styles. It is not affected by the way the way the source code is indented.

Why was I careful to indent the code in Figure 5? To make it easier to follow. If you had to change the code (for example, to add more items), which would you rather work on? The code in Figure 5, or the code in Figure 7?

Good Webers pay attention to source code indenting. It makes site maintenance (that is, changing the content) easier and more accurate.

One final note about this site map:

Simple site map

Figure 3 (again). Simple site map

Here’s a snippet from the source code:

...
#site_map li {
  list-style: none;
  margin: 10px;
}
...
<body>
  <h1>Site Map</h1>
  <ul id="site_map">
...

Figure 4 (again). Code for a simple site map (snippet)

list-style: none; removes the dots from the list items. margin: 10px; adds some space around the items, to separate them a bit. Just makes things look a little better.

Exercise: Site map

Create a site map for Puppy Swarm. It should look like this:

Site map

Upload your solution to your server. Enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

On this page, you learned how to create site maps as nested lists of links.

What now?

We’re done with this lesson! Apart from the exercises. They start on the next page. Do them. You can’t claim you can make links, nav bars, or site maps until you do the exercises.

You know enough to build complete Web sites. Simple, yes, but you could make something that a small business or nonprofit could use as its first site. W00f for you!

Exercises: Web pages with links

You should do the two recommended exercises. Do the optional exercises if you want more practice.

Exercises in the Explore section are more challenging. You may need to use HTML and CSS that isn’t covered in CoreDogs. Get ready to Google!

Recommended

Exercise: Fictional dogs

This is one long exercise that covers all the concepts in this lesson.

You are hired to create a site about fictional dogs.

I don’t know why. Maybe an eccentric millionaire. Maybe as part of a media promotion. Just go with it, OK?

The site will have the following structure:

  • Home page
  • Dogs on screen
    • Dogs in film
    • Dogs on TV
  • Dogs in print
    • Dogs in literature
    • Dogs in comics
  • Dogs on radio
  • Contact page
  • Credits, permissions, terms of use page
  • Site map

Create the directory structure

Here is how the files will be laid out. Create a directory structure to match.

Directories

The library directory contains files that are shared by pages in several parts of the site. fictional-dogs.css will be used by every page.

Create a CSS file

Create a CSS file. Put it in the library.

Choose fonts for the site. Choose font sizes. Set the colors of the heading tags. Set a background color, if you want.

Experiment. Have fun. Be puppy-like.

Create a vertical nav bar

Create a vertical nav bar with rollover effects. Include buttons for the home page, screen, print, and radio. The nav bar should show on the left edge of every page.

The nav bar can be plain text, or you can use images. Here are some images, if you want to use them. You can make your own if you prefer.

Home Home over

Screen Screen over

Print Print over

Radio Radio over

Create a horizontal nav bar for the footer

The footer for each page should look something like this:

Nav bar in footer

It has links to the contact page, the credits, permissions, and terms of use page, and the site map.

Create the home page

It should have the usual stuff. Mine looks like this (shrunk, of course):

Home page

Create the credits, permissions, and terms of use page

This page has three parts to it. Add a table of contents at the top. Mine looks something like this:

Table of contents

Create a site map

Mine looks something like this:

Site map

Upload your solution to your server. Enter the URL of the home page below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Insecting

Create a set of three Web pages about insects.

The first one should look like this:

Beetle page

There’s a 36 pixel heading at the top. Then there’s a horizontal nav bar with three images. Clicking on the first one opens the beetles page. Clicking on the second one shows the butterfly page. Clicking on the third one shows the DIY (do-it-yourself) page.

The buttons in the nav bar have image rollovers:

Beetle rollover

Butterflies rollover

DIY rollover

The butterflies page looks like this:

Butterflies page

The DIY page looks like this when it loads:

DIY page

The first text field has the focus.

The user enters the number of beetles and butterflies s/he wants to make, and the page shows the number of insect parts the user should order. For example:

DIY output

A beetle requires a head, a body, four wings, and six legs. A butterfly requires a head, a body, two wings, and six legs.

Here are some images you can use.

Beetle Beetle

Beetle Beetle

Butterfly

Butterfly

Butterfly

Beetle button Beetle button

Butterfly button Butterfly button

DIY button DIY button

Upload your solution to your server and put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Image quiz

Write three HTML pages that make an animal quiz. Each page shows four images, and asks the user to click on a particular animal.

You can download all of the images in a zip file. The images are sized, and ready to use. Start by downloading the images, and extracting them into a directory.

Here’s the first page, scaled down to fit in this space:

First page

Figure 1. First page

The text says “Click on the dog.”

When the user hovers over an image, the cursor should be a hand:

Hover cursor

Figure 2. Hover cursor

If the user clicks the wrong image, show this:

Wrong

Figure 3. Wrong

The sad face is included in the image zip file.

If the user clicks the right image, show this:

Right

Figure 4. Right

If the user gets it right, the “You got it wrong” message should vanish before the “You got it right” message appears.

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.

The “You got it right” feedback includes a link to the second page. Here it is.

Second page

Figure 5. Second page

The text says “Click on the goose.” The page works the same as the first one.

Here’s the third and last page:

Third page

Figure 6. Third page

The message says “Click on the echinda.”

Here is the “right” feedback for the third page:

Third page

Figure 7. Third page feedback

Hints:

  • Keep all the files together in one directory.
  • Use an external style sheet, linked to all three HTML files.
  • Use a <div> tag to group the tags in a feedback area. E.g.:

<div id="right">
   <img src="lego
   You got it!<br>
   ...
</div>

  • Add a click() event to each image.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Dog teams

Graopugh is a game played by two teams of two dogs each. Each team has a Captain and a Wisher.

Create a site with five pages on it. index.html should look like this:

Home page

Each image links to a page about that dog. Here’s a sample:

Buddy's page

Make a page for each dog.

Use the following images.

Buddy thumbnail

Buddy

Ella thumbnail

Ella

Honeyface thumbnail

Honeyface

Louieeeeee thumbnail

Louieeeeee

Home button

Follow these specifications:

  • Use an external stylesheet.
  • Use a table.
  • Separate the table cells by about 30 pixels.
  • Center the dog names in their cells on the home page.
  • Put a black border around each dog image.
  • The home button image should have no border.
  • Make sure each image has an alt.
  • Use a sans serif font for everything.
  • Make the normal text about 14 pixels high. Make the headings larger.
  • Make the main headings dark green. Make the dog names on the dog pages dark red.
  • Color the team names appropriately.
  • Make the background of every page light yellow.
  • Make the position names on the home page bold.
  • Give every page a title. The home page should have the title “Graopugh Dog Teams.” The dog pages should have titles like “Graopugh Dog Teams: Buddy.”
  • Use only relative links.
  • Use any directory structure you like.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Optional

Exercise: Zombie recognition test

Write a zombie recognition test. It has three pages. The first page is like this:

First page

Figure 1. First page

The background color is #FFFFDD. The header color is #600000. The font is a generic sans serif. The base font size is 14 pixels. Use these styles on all pages.

Click on the link, and see:

The first question

Figure 2. The first question

The screen shot has been scaled down a little to fit on this display.

The user can click on each of the images. Click on a dog, and see:

Wrong

Figure 3. Wrong

Click on the zombie, and see:

Right

Figure 4. Right

Note! If the user clicks on a dog and then the zombie, the screen should look like Figure 4. The “wrong” message should not appear.

Click on the “Next” link, and see:

Done

Figure 5. Done

Other requirements:

  • Make one external CSS style sheet. Use it on all three pages.
  • The mouse cursor should be a hand when it is over an image.
  • There is a horizontal gap between the images.

Here are the images:

Dog

Zombie

Dog

Upload your solution to your server. Enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Explore

These challenging exercises may use HTML not covered in CoreDogs. Get ready to Google!

Exercise: Comparison

Create a page call dog.html, that looks like this:

Dog screen

Here’s the picture:

Renata

Now make a page call cazador.html, that looks like this:

Cazador screen

Here’s the picture:

Cazador

Now make a third page that looks like this:

Screen

Use the <iframe> tag, to insert dog.html and cazador.html inside the third page. You’ll have to Google the tag. You’ll need two of them.

Upload your solution to your server, and enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Many windows

Create four pages. Here’s how they work together:


Hint: Check out JavaScript’s window.open() function.

Upload your solution to your server, and enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Web page layout

You know how to make complex Web pages. You can add text, images, links, tables, nav bars, and so on.

This chapter is about how you group those elements together, to create page layouts.

Most Web pages in a site have the same visual structure, like this:

Page layout

Figure 1. Page layout

Good layouts help users.

Layouts also help site owners.

You create layouts with HTML and CSS, sometimes with a little help from JavaScript. This chapter explains how you do that.

Some advice: use a layout created by a professional Web designer, rather than build your own from scratch. Still, you need to know how layout works, so you can make existing layouts do what you want.

Web page regions

This lesson’s goals

By the end of this lesson, you should:

  • Know what Web page regions are.
  • Know what Webers typically put in each region.

A region is a visual chunk of a Web page. It contains one or more elements. Regions are usually visually distinct from other regions on the page.

Common regions

Web pages are often divided into the following regions:

Regions

Figure 1. Regions

Different things are put in different regions.

  • The top region is often used for site branding (logo and site name). There might be a horizontal nav bar. The top region is often called the header.
  • The left region usually shows a vertical nav bar. The region is also called the left sidebar.
  • The right region might show ads, or more navigation. The right region is also known as the right sidebar.
  • The bottom region might have copyright information, and another nav bar. The region is often called the footer.
  • The main content of a page usually goes in the center region.

Not all sites are like this. CoreDogs isn’t, for example. CoreDogs is like this:

Regions in CoreDogs

Figure 2. Regions in CoreDogs

But the regions in Figure 1 are common.

Here’s a layout that uses three regions.

Regions example

Figure 3. Regions

The top region has the logo, the site name, and a nav bar. The center region has a page header and content. The bottom region has a nav bar. The left and right regions are not used.

Exercise: Finding regions

Web sites use some common layout patterns. Find at least two examples of each of the following. Enter the URLs in the solution area.

Five regions
Five regions

No right region
No right region

No left region
No left region

No right or left regions
No right or left regions

Put the URLs below, like this:

Five regions:

URL 1
URL 2

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

  • Web page regions are visual areas on a Web page, like top, left, and center.
  • Regions have common uses. For example, left regions are often used for nav bars.

What now?

Here’s a layout again:

Regions example

Figure 3 (again). Regions

To create this, you need to set the spacing around regions. Let’s see how you do that.

Spacing between elements

Where are we?

You make layouts by creating regions. Regions are visual chunks:

Regions example

Figure 1. Regions

One thing you need to do is set the spacing around regions. This lesson shows you how.

This lesson’s goals

By the end of the lesson, you should:

  • Know what the box model is, and how to use it.
  • Know how to set margin and padding defaults.
  • Know how CSS overrides work.
  • Know how containership affects layout.

The box model

Browsers draw HTML block elements, like <p>, <div>, and <h1>, in boxes. The boxes might not be visible, but they are still there.

The “box model” shows how boxes work. Here’s an example we looked at earlier.

Box model

Figure 2. The box model

Here’s how I created this box:

.big_margin_padding {
  margin: 20px;
  padding: 20px;
  border: dotted 2px #668014;
}
...
<img class="big_margin_padding" ...>

Figure 3. CSS for the dog box

padding is the gap between the content (an <img> tag in this case) and the border. margin is the gap between the border and the box’s edge.

This:

margin: 20px;

sets the same margin on all sides of the element: top, right, bottom, and left.

You can set the values individually for margin and padding, like this:

.different_margins {
  margin-top: 20px;
  margin-right: 10px;
  margin-bottom: 0;
  margin-left: 5px;
}

Figure 4. Separate values

If a gap is zero (like margin-bottom above), you don’t need to add the px.

You can put the values on one line, like this:

.different_margins {
  margin: 20px 10px 0 5px;
}

Figure 5. Separate values on one line

How to remember which number is which? The first number is for the top, and then go clockwise from there:

Which margin is which

Figure 6. Which margin is which

This works for both margin and padding.

Exercise: Dog spacing

Here’s an image:

A dog

Figure 1. A dog

Write a page that looks like this:

Dog spacing

Figure 2. Dog spacing

The margins are all 10px. The padding is 10px on each side, except for the bottom, where it’s 30px. The border is 2px wide, dotted, with a color code of #BBBBBB.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Margin and padding defaults

Browsers have defaults for margin and padding. So if you don’t specify margin and padding, the browser adds them for you.

Usually this works just fine. But when you do page layouts, the defaults can be a problem. Different browsers use different defaults, so a layout that works in one browser can look strange in another.

Webers often add “reset styles” to deal with the problem. For example, you might find this at the top of a page:

* {
  margin: 0;
  padding: 0;
}

Figure 7. A reset rule

The * is the CSS universal selector. It selects every type of tag on the page. This rule gives every element no padding and no margin.

If you do this, you might add margin and padding back to some elements, creating your own defaults for the page. For example:

* {
  margin: 0;
  padding: 0;
}
p {
  margin: 10px 0 10px 0;
}
img {
  margin: 10px;
  padding: 10px;
}

Figure 8. Reset and set known defaults

Every <p> and <img> on the page will use these values. Unless you add other rules.

Overriding

The defaults apply unless you override them for specific elements. Suppose I had this code.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>CSS Override</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style type="text/css">
      * {
        margin: 0;
        padding: 0;
      }
      body {
        font-family: "Trebuchet MS", sans-serif;
        font-size: 14px;
      }
      img {
        margin: 20px;
        padding: 5px;
        border: 2px dotted #008000;
      }
      #beet {
        background-color: #B2C3CF;
        margin: 5px;
        padding: 5px;
        border: 3px black double;
      }
    </style>
  </head>
  <body>
    <h1>CSS Override</h1>
    <p><img id="bear" src="bear.png" alt="Bear"></p>
    <p><img id="beet" src="beet.png" alt="Beet"></p>
  </body>
</html>

Figure 9. Overrides

There are five elements on the page: an <h1>, two <p>s, and two <img>. The browser applies styles to each one, based on the CSS.

Have a look at beet, the second image in line 31. What style rules apply to it? These rules:

  • Lines 7-9: This rule applies to everything, so it applies to beet.
  • Lines 11-14: This rule applies to everything in the <body>, so it applies to beet.
  • Lines 15-19: This rule applies to all <img>s. beet is an <img>, so the rule applies to beet.
  • Lines 20-25: This rule applies to everything with an id of beet. So, of course, it applies to beet.

So all of these rules apply. But the rules conflict. For example:

  • Line 8: margin: 0;
  • Line 16: margin: 20px;
  • Line 22: margin: 5px;

What does the browser do? The answer: it applies the most specific rule. The most specific rule is the one that applies just to beet (lines 20 to 25). The next most specific rule is the one that applies to all <img>s (lines 15 to 19). The least specific rule is the one that applies to all elements on the page (lines 7 to 9).

So we would expect the browser to use line 22, and give beet a margin of 5px. Here is what the browser shows:

Overriding margin

Figure 10. Overriding margin

You can see that the gap from the left of the screen to the beet (5px, from line 22) is smaller than the gap from the left to the bear (20px, from line 16). This is what we expect.

You can try the page.

Renata
Renata

In the CSS code, the rule for beet comes after the others. Does that make a difference to what rule the browser uses?

Kieran
Kieran

No, it doesn’t make a difference. Move the #beet {} rule to the top, and it would look the same. It’s the specificity that matters.

Exercise: Spacing for dead dudes

Here are some dead dudes:

Ferdinand de Soto

Ferdinand Magellan

Francisco Pizarro

Create a page that looks like this:

Spacing for dead dudes

Figure 1. Spacing for dead dudes

The spacing around the images is 5px, except for the middle one. That’s 20px.

Use exactly this HTML:

<p>
  <img src="Ferdinand_de_Soto.png" alt="Ferdinand de Soto"><br>
  Ferdinand de Soto
</p>
<p id="magellan">
  <img src="Ferdinand_Magellan.png" alt="Ferdinand Magellan"><br>
  Ferdinand Magellan
</p>
<p>
  <img src="Francisco_Pizarro.png" alt="Francisco Pizarro"><br>
  Francisco Pizarro
</p>

Figure 2. Dead dude HTML

Use CSS overriding to redefine Magellan’s look.

Hint: Mess with the styles for <p> tags in this exercise, not the styles for the <img> tags.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Containers

An important part of layout is knowing how to nest elements. You’ve already seen this in lots of examples, though you might not have noticed. But when laying out pages, you have to pay attention to nesting.

Each element is inside a container. The outer visible container is the <body> element. Everything is inside that. In your HTML, elements are inside <div>s, <p>s, <blockquote>s, and other tags.

Here’s a line from Figure 9.

<p><img id="bear" src="bear.png" alt="Bear"></p>

The <img> is contained in the <p>.

CC
CC

What about headings? Like this:

<h1>Sheltie Habits</h1>
<p>Shelties bark a lot. A <em>lot</em>.</p>

You get:

Headings

The text “Shelties bark a lot” looks like it’s contained in the section “Sheltie Habits.”

Kieran
Kieran

Good question.

The word “contained” has more than one meaning. I’m talking about structural containership. You get structural containership when HTML tags are nested inside each other.

In this code:

<h1>Sheltie Habits</h1>
<p>Shelties bark a lot. A <em>lot</em>.</p>

the <p> tag is not structurally contained in the <h1>.

CC
CC

Oh, I see. But the <em> is contained in the <p>, right?

Kieran
Kieran

Yes! The start and end of the <em> tag are both inside the <p> tag.

CC
CC

But as far as the meaning of the page goes…

Kieran
Kieran

Right! The look of the page, with the heading being in a large font, makes it clear to users that the concept in “Shelties bark a lot” belongs to the topic “Sheltie Habits.”

Renata
Renata

Because that’s what we’re used to seeing.

Kieran
Kieran

Yes, exactly. Newspapers, books, use this convention. Big text for headlines and section headings, smaller text for stuff that belongs under those headings.

But this is just a convention we’ve gotten used to. A shared habit, if you like. There’s nothing in the HTML that says that the <p> is part of the <h1>.

When a tag is contained in another, the outer tag is drawn first, and then the inner tag is drawn inside it. This means that the margins and padding applied to the outer tag move the entire inner tag around.

Let’s say we had this:

<div id="outer">
  <p id="walrus">Walrus</p>
  <div id="inner1">
    <p id="hippo">Hippo</p>
  </div>
  <div id="inner2">
    <p id="dog">Dog</p>
  </div>
  <div id="inner3">
    <p id="cat">Cat</p>
    <div id="inner3_inner">
      <p id="bird">Bird</p>
    </div>
  </div>
</div>

Figure 11. HTML containers

Everything is inside outer. Some things are nested deeply. bird is inside inner3_inner is inside inner3 is inside outer.

Here’s some CSS to go along with Figure 11.

* {
  margin: 0;
  padding: 0;
}
#outer {
  margin: 10px;
  padding: 12px;
  border: 2px dotted #B7B2CF;
}
#inner1 {
  background-color: #B2C3CF;
  margin: 20px;
  padding: 30px;
  border: 1px solid black;
}
#inner2 {
  margin: 20px;
  padding: 10px;
}
#inner3 {
  margin: 5px;
  padding: 10px;
  border: 2px #008000 dashed;
}
#inner3_inner {
  margin: 10px;
  padding: 8px;
  border: solid blue 1px;
  background-color: #CFC9B2;
}

Figure 12. CSS for the HTML containers

Here’s what you get:

Result

Figure 13. Result

The position of an element depends on its margins and padding, and the margins and padding of its containers.

Containers are also called parents. So inner3_inner is a parent of bird.

The browser gets this (line 12 of Figure 11):

<p id="bird">Bird</p>

It shows the text “Bird,” somewhere on its window. Let’s see if we can figure out how far the text “Bird” should be from the left edge of the browser’s window.

bird is inside inner3_inner. inner3_inner has a margin of 10 pixels, padding of 8, and a 1 pixel border. That’s 10 + 8 + 1 = 19 pixels so far.

inner3_inner is inside inner3. inner3 has a margin of 5 pixels, padding of 10, and a 2 pixel border. That’s 5 + 10 + 2, plus the 19 pixels we had earlier. That’s 36 pixels.

inner3 is inside outer. outer has a margin of 10 pixels, padding of 12, and a 2 pixel border. That’s 36 (from before) + 10 + 12 + 2 = 60 pixels.

So the text “Bird” should be 60 pixels from the left of the document.

Renata
Renata

The text “Bird” is inside a <p> tag:

<p id="bird">Bird</p>

Wouldn’t that add some spacing to the left?

CC
CC

Oo, oo! Can I answer?

Kieran
Kieran

OK.

CC
CC

There’s a reset:

* {
   margin: 0;
   padding: 0;
}

So the <p> has no margin or padding.

Kieran
Kieran

That’s right!

So we’ve worked out that the text “Bird” should be 60 pixels from the left. How do we tell what actually happens?

I add some JavaScript to the page. Try it. Move the mouse over each text element, and you’ll see the left and top position of each one. “Bird” is where we thought it should be. W00f!

Exercise: Where are the animals?

Go through the CSS on the animal names page. Work out what you think the top and left position of each animal name should be (for walrus, hippo, etc.). Then compare it with what the page actually does.

Below, type in the positions you worked out, and what the page actually does.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

In this lesson, you learned:

  • What the box model is, and how to use it.
  • How to set margin and padding defaults.
  • How CSS overrides work.
  • How containership affects layout.

What now?

Now you know how to add space around elements. You can use margin and padding with page regions (like top, left, right, etc.).

Now let’s see how to move regions to the left and right.

Moving regions left and right

Where are we?

You know how to add space around an element. Let’s see how you can move an element to the left or right of a page. This is how you position the left and right regions in a page layout.

This lesson’s goals

By the end of this lesson, you should:

  • Know what floating an element means.
  • Know how to set the width of floated elements.

Floating text

We talked about floating images before. You can also use the float property with entire sections of a page. This lessons digs into float a little more.

Let’s start with this page:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Floating</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style type="text/css">
      * {
        margin: 0;
        padding: 0;
      }
      body {
        font-family: "Trebuchet MS", sans-serif;
        font-size: 14px;
      }
      p {
        margin: 5px;
        padding: 5px;
      }
      #text2 {
        color: #00A000;
        border: 2px dotted #00A000;
      }
    </style>
  </head>
  <body>
    <h1>Floating</h1>
    <p id="text1">I am text 1.</p>
    <p id="text2">I am text 2.</p>
    <p id="text3">I am text 3.</p>
    <p id="text4">I am text 4.</p>
    <p id="text5">I am text 5.</p>
  </body>
</html>

Figure 1. Floatless

It looks like this:

Floatless, rendered

Figure 2. Floatless, rendered

This is normal flow. HTML elements are drawn on the page in the order they appear in the HTML file.

Let’s mess with text2. Change its CSS to:

#text2 {
  color: #00A000;
  border: 2px dotted #00A000;
  float: right;
}

Figure 3. The first float

Line 22 is new. Here’s what it produces:

The first float, rendered

Figure 4. The first float, rendered

When an element has a float, it is taken out of the normal flow. Everything below it is moved up. So when text2 floated, text3 moved up.

What happens to the floated element? It’s pushed to the left or right of the browser window, depending on whether it was float: left; or float: right;. Figure 3 used a float: right;, so text2 goes to the right.

I shrank the browser window for the screen shot.

You can try it.

Here’s what happens when I tell text2 to float: left.

#text2 {
  color: #00A000;
  border: 2px dotted #00A000;
  float: left;
}

Figure 5. Float left

Float left, rendered

Figure 6. Float left, rendered

When you float something, the normal elements wrap around the floated one. That’s what text3 and text4 are doing.

Let’s float both text2 and text3.

#text2, #text3 {
  color: #00A000;
  border: 2px dotted #00A000;
  float: right;
}

Figure 7. Two float

Two float, rendered

Figure 8. Two float, rendered

They float together.

But look carefully at the screen shot. text3 is to the left of text2. That’s because text2 was the first thing to float, and it got pushed to the right. Then text3 was floated, and it was pushed to the right. But it couldn’t go as far, because text2 was already there.

Let’s float them to the left.

#text2, #text3 {
  color: #00A000;
  border: 2px dotted #00A000;
  float: left;
}

Figure 9. Two float left

Two float, rendered

Figure 10. Two float left, rendered

I added another text element, so you could see that the wrapping was working.

Now, suppose I wanted 2 and 3 next to each other, but wanted 4 and 5 to start below them, like this:

Separating 4 and 5, rendered

Figure 11. Separating 4 and 5, rendered

I would add this rule:

#text2, #text3 {
  color: #00A000;
  border: 2px dotted #00A000;
  float: left;
}
#text4 {
  clear: left;
}

Figure 12. Separating 4 and 5, code

The clear: left; in line 25 tells the browser that there should be no floated stuff to the left of text4. This puts text4 in its own line, and everything flows normally from there.

Exercise: Conversation

Here are some images for this exercise:

CC

Renata

Create a page like this:

Conversation

Figure 1. A conversation

Start with this code:

img.conversation {
   float:
   clear:
   margin: 10px;
}
p.conversation {
   float:
   clear:
}
...
<img class="conversation" src="cc.jpg" alt="CC">
<p class="conversation">Hi, Renata. What's shakin'?</p>

clear is the key to this exercise. Think about what doesn’t have stuff to the left, and what doesn’t have stuff to the right.

Upload your solution to your server. Add the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

B things

Here’s another example that combines floating with containership and overriding. Suppose we want this:

B things

Figure 13. B things

Here’s some code:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Floating</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style type="text/css">
      * {
        margin: 0;
        padding: 0;
      }
      body {
        font-family: "Trebuchet MS", sans-serif;
        font-size: 14px;
      }
      p {
        margin: 10px;
        padding: 10px;
        clear: left;
      }
      .b_thing {
        margin-left: 20px;
        border: dotted 2px #888888;
        float: left;
        clear: none;
      }
    </style>
  </head>
  <body>
    <h1>Floating</h1>
    <p>Here are some B things.</p>
    <p class="b_thing">
      <img src="blueberries.png" alt="Blueberries" align="middle">
      Blueberries
    </p>
    <p class="b_thing">
      <img src="buffalo.png" alt="Buffalo" align="middle">
      Buffalo
    </p>
    <p>They are some B things.</p>
    <p>Did you like the B things?</p>
  </body>
</html>

Figure 14. B things code

Look at the HTML first. Lines 31 to 34 create the blueberries container. It has an image and some text.

The blueberries image and text have a border drawn around them both. This is because the border is drawn around their container, not the individual elements. The container is the <p> the image and text are inside. That <p> has class="b_thing". The class has a border (line 22).

The blueberries image and text also float together. Again, it’s because they’re in a container, and the container is floated.

Understanding that containers can be moved around is a key to making layouts. You groups elements together into a container, and then move the container where you want it.

Onward.

Lines 15 to 19 set the style for the <p> tag. All <p>s will get margins and padding, and nothing will float to their left (line 18).

Lines 20 to 25 override some of those settings for <p>s that have the class b_thing. The left margin is increased a little, a dotted border is set, and they’re floated. The clear: none; overrides the clear: left; in line 18.

Let’s explore two of these settings, so you can see why I used them. First, let’s look at the margin-left. Without it, the page looks like:

No extra left margin

Figure 15. No extra left margin

Normal paragraphs don’t have a border; only b_things do. That’s why Figure 15 looks like the border on b_things juts out to the left. It doesn’t really jut out, it just looks that way because the other <p>s don’t have borders.

I thought it looked better when the border lined up vertically with the text above and below it:

B things

Figure 13 (again). B things

So I added the extra margin space on the left of b_things.

Now let’s look at that clear. Here are the rules again.

p {
  margin: 10px;
  padding: 10px;
  clear: left;
}
.b_thing {
  margin-left: 20px;
  border: dotted 2px #888888;
  float: left;
  clear: none;
}

Part of Figure 14 (again). B things code

Suppose I dropped clear: none; (line 24):

p {
  margin: 10px;
  padding: 10px;
  clear: left;
}
.b_thing {
  margin-left: 20px;
  border: dotted 2px #888888;
  float: left;
}

Figure 16. clear:none; gone

Here’s what I would get:

clear:none; gone, rendered

Figure 17. clear:none; gone, rendered

The two b-things are no longer next to each other. Why? Because the clear: left; in the rule for the <p> tag (line 18) applies to them as well. They’re <p>s. Remember that clear: left; tells the browser not to let anything float to the left. So nothing is allowed to float to the left of the buffalo.

Adding clear:none; in line 24 overrides the clear: left; setting in line 18. But only for elements with the class b-thing.

Renata
Renata

This is starting to make my brain hurt.

CC
CC

Mine too.

Kieran
Kieran

Mine too. This can get very complicated.

In practice, when I create a new Web site, I borrow a layout from a Webber who is a CSS expert.

CC
CC

So why are we learning this?

Kieran
Kieran

Because you’ll need to change what the Weber created, to add your own branding and such. I recommend making small changes only. But you will still need to move things around.

More on this later.

Floats and widths

Earlier, we saw this code:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Floating</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style type="text/css">
      * {
        margin: 0;
        padding: 0;
      }
      body {
        font-family: "Trebuchet MS", sans-serif;
        font-size: 14px;
      }
      p {
        margin: 5px;
        padding: 5px;
      }
      #text2 {
        color: #00A000;
        border: 2px dotted #00A000;
      }
    </style>
  </head>
  <body>
    <h1>Floating</h1>
    <p id="text1">I am text 1.</p>
    <p id="text2">I am text 2.</p>
    <p id="text3">I am text 3.</p>
    <p id="text4">I am text 4.</p>
    <p id="text5">I am text 5.</p>
  </body>
</html>

Figure 1 (again). Floatless

It looks like this:

Floatless, rendered

Figure 2 (again). Floatless, rendered

That dotted area. How wide is it? Let’s look at the entire browser window.

Floatless, rendered

Figure 18. Floatless, the entire window

That dotted area stretches across the entire window.

The CSS property width sets the width of an element. Like this:

width: 200px;

But what if you don’t use the width property? The browser uses the default. The default for width is to make the element stretch across the entire window. That’s why Figure 18 looks as it does.

Well, kind of. It’s a bit more complicated. The default width actually depends on whether the element is floated.

Here’s some more code.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Widths</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style type="text/css">
      * {
        margin: 0;
        padding: 0;
      }
      body {
        font-family: "Trebuchet MS", sans-serif;
        font-size: 14px;
      }
      p {
        margin: 5px;
        padding: 5px;
        border: 2px dotted #00A000;
      }
      #text2 {
        float: left;
      }
      #text3 {
        width: 200px;
        clear: left;
      }
      #text4 {
        width: 200px;
        float: left;
        clear: left;
      }
    </style>
  </head>
  <body>
    <h1>Widths</h1>
    <p id="text1">I am text 1. No width, no float.</p>
    <p id="text2">I am text 2. No width, float.</p>
    <p id="text3">I am text 3. Width, no float.</p>
    <p id="text4">I am text 4. Width, float.</p>
  </body>
</html>

Figure 19. How width and float interact

Here’s what you get:

widths and floats rendered

Figure 20. widths and floats rendered

text1 and text2 show the differences in default widths. text1 shows that when there is no float, the default width is to stretch across the page. text2 shows that when there is a float, the default width is to take just enough space to fit the content. You won’t be able to predict the width very easily.

text3 and text4 shows what happens when you give a width. You get the width you ask for.

Exercise: Non-table Table

Here are some images to use for this exercise:

CC

CC

Renata

Renata

Create a page that looks like this:

Non-table table

Figure 1. Non-table Table

But don’t use the table tag!

Here’s some HTML to get you started:

<p class="start_of_row">
  <img src="cc1.jpg" alt="CC"><br>
  This is CC.
</p>
<p>
  <img src="cc2.jpg" alt="CC"><br>
  This is CC, too.
</p>

Figure 2. HTML

The class start_of_row starts a new row in the table. There is nothing to the left of a cell that is the first in a row.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

But wait, there’s…

...more. A lot more. For example, what happens when you give an element a width that’s too narrow to fit its content? Maybe you put an image that’s 250px wide into a <p> that’s only 200px wide.

Well, it depends. The image might stick outside of its container. The image might be cut off. There might even be a scroll bar! It depends on other settings.

We’re not going to go over all of the details. But I hope you’re getting that idea that CSS layout can be hard to do.

Simple modifications of an existing layout, well, you’ll be able to handle that. But doing anything complicated from scratch can be frustrating.

Summary

  • Floating an element takes it out of normal flow.
  • Floated elements move left or right. Other elements wrap around them.
  • The clear property lets you control whether things are allowed to float to the left or right of an element.
  • By default, floated elements take just enough space to show them.

What now?

So you make a layout, but it doesn’t look right. Figuring out what is causing the problem can be a pain. Could be a margin, could be a padding. Maybe a float doesn’t do what you expect.

Let’s look at some tools that can help.

Diagnosing layout problems

Where are we?

You know how to add spacing around elements, float elements to the left and right, and set element widths. You’ll use these three things to make layouts.

But it’s easy to make mistakes in CSS, and sometimes it’s hard to find out what caused the mistakes. Let’s look at some tools that can help.

This lesson’s goals

By the end of this lesson, you should know that:

  • Editors like Netbeans help you spot typing errors before they get into your code.
  • The “MeasureIt”“:https://addons.mozilla.org/en-US/firefox/addon/539 add-on helps you figure out where the browser is putting things.

Argh!!

Getting pages exactly right with CSS can be tough. Why?

CSS is hard

It’s easy to do a simple layout with CSS. But complex layout, like CoreDogs? Argh!!

CSS has lots of strange quirks. Things you think should be easy, aren’t. Like vertical centering.

Containership and overriding can lead you astray. You might think you know what rule applies to an element. But the element could be affected by a rule you hadn’t thought about.

Cross-browser problems

CSS that works in one browser might not work in another. You’ve already seen that browsers use different defaults for margin and padding. But that’s just the tip of the iceberg.

Typos

Here are some typos in code:

margins: 10px;

background_color: blue;

padding 10px 5px 10px 5px;

The errors are easy to spot in isolated lines. Put them in a 100-line CSS file, and they’re hard to find.

Here are tools that can help you find mistakes.

Editors

Some editors spot some typing errors. Here’s a screen shot from Netbeans:

Error spotted

Figure 1. Error spotted

The Netbeans editor knows that margins is not a CSS property. I meant to type margin.

Download Netbeans. This one feature will save you a lot of time.

CSS validator

You can ask the W3C’s CSS validator to check your CSS. The validator is at http://jigsaw.w3.org/css-validator/.

For example:

Validator input

Figure 2. Validator input

Validator output

Figure 3. Validator output

Firebug

Firebug is an add-on for Firefox. It does many things. One of the most useful is showing you what CSS styles the browser is using on an element.

Suppose I wanted to find out the styles that the browser applied to Bird:

What styles?

Figure 4. What styles?

I would look at the page in Firefox, then press F12 to start Firebug (assuming I’ve installed Firebug, of course). Then I’d click the inspect button:

Inspect button

Figure 5. Inspect button

As I move the mouse over different HTML elements, Firebug shows where the element is in the HTML, and what styles apply to it:

Firebug showing HTML and CSS

Figure 6. Firebug showing HTML and CSS

You should install Firebug today. It’s free.

Web developer add-on

Web Developer is another good free add-on for Firefox. Let’s look at just one of the many Good Things it does.

Suppose I’m looking at this page:

Elements

Figure 7. Elements

I want to move things about, so I want an easy way to see the elements I can set padding and margins on. I can tell Web Developer to add outlines to the block elements:

Web Developer menus

Figure 8. Web Developer menus

It will show:

Outlined elements

Figure 9. Outlined elements

Measuring

Sometimes you want to know exactly how many pixels wide something is, or what the gap is between two elements. The MeasureIt add-on is handy.

It adds a button to the Firefox status bar. Click on it:

MeasureIt button

Figure 10. MeasureIt button

Drag the mouse, and see the size:

MeasureIt output

Figure 11. MeasureIt output

Exercise: Validating CSS

Here’s some CSS:

* {
  margin: 0;
  padding: 0;
}
body {
  font-family: Verdana, Helvetica, sans-serif;
  font-size: 14px;
  background_color: #ffeaff;
  width 750px;
  margin: 5px auto 5px auto;
}
#top_region {
  background-color: #E0E0E0;
}
#left_region {
  float: left;
  width: 120px;
  background-color: #defe2;
}
#center_region {
  margin-left: 120px;
  margin-right: 120px;
  background-color: #fdffca;
}
#right_region {
  float: rght;
  width: 120px;
  background-color: #ddddff;
}
#bottom_region {
  backgound-color: #E0E0E0;
}

Figure 1. Some CSS

Check it with theW3C’s CSS validator. What problems are there?

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

Errors in CSS can be hard to spot. There are tools that can help.

  • An editor like Netbeans can check your typing.
  • MeasureIt is a Firefix add-on that helps you figure out exactly how things are positioned.

What now?

All the pieces are in place. Let’s see how you can make a liquid layout.

Liquid layouts

Where are we?

You know how to set spacing around regions, and how to float regions left and right. Let’s put these things together to make complete page layouts.

This lesson’s goals

By the end of this lesson, you should:

  • Know that a Web page with a liquid layout changes its width when the browser window changes its width.
  • Know how to create liquid layouts with and without whitespace.

What is a liquid layout?

A liquid layout expands horizontally to fill the browser window. Usually it’s the center region that expands. Liquid layouts are also called fluid layouts.

Liquid layout

Figure 1. Liquid layout

Liquid layouts use as much of the browser window as they can. However, the width of the center region is unpredictable. Many designers prefer fixed layouts, where they have better control. We’ll look at fixed layouts later.

Liquid layout, no white space

Let’s start by creating a page that looks like this:

Liquid layout, no whitespace

Figure 2. Liquid layout, no whitespace

The page has five regions: top, left, center, right, and bottom. There is no whitespace between the regions, or inside the regions. We’ll change that later.

You can try the page. Resize the browser window, and watch the center region change its size.

CC
CC

When I use the Web, I maximize my browser window, and keep it that way. My guess is that most people work the same way.

Why bother making a liquid layout when people don’t change the size of their browser windows?

Kieran
Kieran

Good question! It’s not really about what happens when people resize browser windows. It’s about making the site look good for different people.

Someone might have his screen set to 1,024 pixels x 768 pixels. Someone else might have her screen set to 1,280 × 1,024. A liquid layout will adjust itself to use whatever is available on each machine.

Resizing the browser window just lets you see that a layout is adapting.

Here is the code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Liquid layout</title>
    <style type="text/css">
      * {
        margin: 0;
        padding: 0;
      }
      body {
        font-family: Verdana, Helvetica, sans-serif;
        font-size: 14px;
      }
      #top_region {
        background-color: #E0E0E0;
      }
      #left_region {
        float: left;
        width: 120px;
        background-color: #defee2;
      }
      #center_region {
        margin-left: 120px;
        margin-right: 120px;
        background-color: #fdffca;
      }
      #right_region {
        float: right;
        width: 120px;
        background-color: #ddddff;
      }
      #bottom_region {
        background-color: #E0E0E0;
      }
    </style>
  </head>
  <body>
    <div id="top_region">
      <p>Top region</p>
    </div>
    <div id="left_region">
      <p>Left region</p>
    </div>
    <div id="right_region">
      <p>Right region</p>
    </div>
    <div id="center_region">
      <p>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. </p>
    </div>
    <div id="bottom_region">
      <p>Bottom region</p>
    </div>
  </body>
</html>

Figure 3. Code for liquid layout with no whitespace

Let’s look at the HTML first. It’s simple. Each region has its own <div> with a unique id. That’s it!

The CSS does all the work. Lines 18 to 22 style the left region:

#left_region {
  float: left;
  width: 120px;
  background-color: #defee2;
}

Line 19 uses the float property. float removes the left region from the normal flow of the HTML, and sends it to the left of the page. The width is fixed at 120px. It will stay that way as the browser window is resized.

Lines 28 to 32 style the right region:

#right_region {
  float: right;
  width: 120px;
  background-color: #ddddff;
}

It’s sent to the right, and given a fixed width.

The center region is styled by lines 23 to 27:

#center_region {
  margin-left: 120px;
  margin-right: 120px;
  background-color: #fdffca;
}

It doesn’t have a width property set, so it’s free to expand to fill the browser width. The left and right margins are set to allow for the left and right regions.

You can try the page. Resize the browser window, and watch the center region change its width. The top and bottom regions expand and contract as well, since they have no width in their CSS rules.

Exercise: Liquid, no right region

Make a page with a liquid layout and no right region. It should have top, bottom, left, and center regions. Like this:

Liquid, no right

Figure 1. Liquid, no right

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Liquid layout, white space

Let’s add some whitespace around each of the regions. We want to end up with something like this:

Liquid layout with whitespace

Figure 4. Liquid layout with whitespace

Each region has both padding and margins. Remember the difference:

Margins and padding

Figure 5. Margins and padding

Margins are outside the border of an element. Padding is inside the border of an element, between the border and the element’s content.

When we add margins and padding to regions, we may need to adjust other regions to allow for the extra space. So if we add space to the left and right regions, we need to adjust the margins of the center region.

Here’s some CSS that will do the job. The rest of the page is the same as before, in Figure 3. You can try the page.

#top_region {
  background-color: #E0E0E0;
  padding: 5px;
  margin: 5px;
}
#left_region {
  float: left;
  width: 120px;
  background-color: #defee2;
  padding: 5px;
  margin: 0 5px 5px 5px;
}
#center_region {
  margin: 0 140px 5px 140px;
  background-color: #fdffca;
  padding: 5px;
}
#right_region {
  float: right;
  width: 120px;
  background-color: #ddddff;
  padding: 5px;
  margin: 0 5px 5px 5px;
}
#bottom_region {
  background-color: #E0E0E0;
  padding: 5px;
  margin: 0 5px 0 5px;
}

Figure 6. Adding whitespace

The top region has padding and margins added:

#top_region {
  background-color: #E0E0E0;
  padding: 5px;
  margin: 5px;
}

This will add margins to all sides of the region.

The left region is immediately below the top region. We want the same sized gap above the top region and between the top and left, like this:

Margin goal

Figure 7. Margin goal

Both of the gaps are five pixels.

Suppose we used the following rule for the left region:

#left_region {
  float: left;
  width: 120px;
  background-color: #defee2;
  padding: 5px;
  margin: 5px;
}

Figure 8. Bad rule, naughty rule

This would seem to make sense. margin: 5px; in line 11 would add five pixels all around.

The problem is that the top region already has a five pixel margin below it. Add a five pixel margin to the top of the left region, and you get this:

Margin goal

Figure 9. Wrong margin

There will a 10 pixel gap between the top and left regions. Five pixels for the bottom margin of the top region, and another five pixels for the top margin of the left region.

To fix it, set the top margin of the left region to zero:

#left_region {
  float: left;
  width: 120px;
  background-color: #defee2;
  padding: 5px;
  margin: 0 5px 5px 5px;
}

Figure 10. Good margin

Line 11 has four values. Remember that they are applied in clockwise order from the top.

Margin order

Figure 11. Margin order

This fixes the problem, giving us the five pixel gap we wanted.

The same approach is used for the other regions.

The center region has been adjusted a little:

#center_region {
  margin: 0 140px 5px 140px;
  background-color: #fdffca;
  padding: 5px;
}

Figure 12. Center

The left and right margins in line 30 allow for the extra whitespace around the left, center, and right regions.

In this section, you’ve seen how you can add whitespace around regions. When you add whitespace to a floated region (like the left region), you might need to adjust the spacing of other regions (like increasing the left margin of the center region).

Borders are the same. If you add borders to the left region, you would have to think about how that affects the left margin of the center region.

Exercise: Liquid, no right region, with spacing and shadow

Make a liquid page like this:

Liquid layout

Figure 1. Liquid layout

It has top, left, center, and bottom regions. There’s a 5px gap between them.

The left region has a shadow effect. It was created by applying a 3px border to the bottom and right of the region. Here’s some CSS:

border-width: 0 3px 3px 0;
border-color: #AAAAAA;
border-style: solid;

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Variations

You can change the basic layout in many ways. Here are some possibilities.

The footer is often used for copyright notices, “About us” links, and other random things. It’s often given a smaller font, and centered on the page. Like this:

Footer centered

Figure 13. Footer changes

Here are the changes.

#bottom_region {
  background-color: white;
  padding: 5px;
  margin: 0 5px 0 5px;
  text-align: center;
  font-size: 12px;
}
...
<div id="bottom_region">
  <hr>
  <p>Bottom region</p>
</div>

Figure 14. Footer changes

Line 5 pushes the text into the center. Line 6 reduces the font size. The horizontal line is created by an <hr> in line 10.

Exercise: Making the line

Create a page that looks like this:

Layout

Figure 1. Layout

Don’t use an <hr> tag to make the line at the top of the bottom region. Instead, set the line using the CSS border property.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Another way to change the footer is to move it under the center region, like this:

Footer under center region

Figure 15. Footer under center region

Here is the change:

#bottom_region {
  background-color: white;
  padding: 5px;
  margin: 0 5px 0 140px;
  font-size: 12px;
}

Figure 16. A different footer change

The difference is in line 4. It was:

margin: 0 5px 0 5px;

Now it’s:

margin: 0 5px 0 140px;

Just the left margin is different.

Tall left region

Sometimes the left region is as tall as the page. It includes logos and other things that are normally in headers. Like this:

Tall left region

Figure 17. Tall left region

Here’s some code:

#top_region {
  background-color: #E0E0E0;
  padding: 5px;
  margin: 5px 5px 5px 140px;
}
...
#bottom_region {
  background-color: white;
  padding: 5px;
  margin: 0 5px 0 140px;
  font-size: 12px;
}
...
<div id="left_region">
  <p id="logo">Logo</p>
  <p class="menu_item">Menu item</p>
  <p class="menu_item">Menu item</p>
  <p class="menu_item">Menu item</p>
</div>
<div id="top_region">
  <p>Top region</p>
</div>

Figure 18. Code for tall left region

Line 4 moves the top region to the right. Line 10 does the same for the bottom region.

How does the left region get so tall? There are no changes to the CSS. It’s the HTML that changes. Before, we had:

<div id="top_region">
...
</div>
<div id="left_region">
...
</div>

Now it’s:

<div id="left_region">
...
</div>
<div id="top_region">
...
</div>

The left region is floated out of normal flow, and then the top region is added. It wraps around the floated content, that is, the left region.

Top menu region

You can add new regions to layouts. For example, let’s create a separate region for the top menu, like this:

Top menu region

Figure 19. Top menu region

Here’s what we had before:

#top_region {
  background-color: #E0E0E0;
  padding: 5px;
  margin: 5px;
}

Part of Figure 6 (again). Adding whitespace

Note the changes in the whitespace. The top region has no whitespace at the bottom. The new menu region has space on all sides except for the top.

Here’s what we change the code to:

#top_region {
  background-color: #E0E0E0;
  padding: 5px;
  margin: 5px 5px 0 5px;
}
#top_menu_region {
  background-color: #F0F0F0;
  text-align: center;
  padding: 5px;
  margin: 0 5px 5px 5px;
}
...
<div id="top_region">
  <p>Top region</p>
</div>
<div id="top_menu_region">
  <p>Menu item | Menu item | Menu item</p>
</div>

Figure 20. Code for top menu region

The whitespace changes are in lines 4 and 10.

Summary

  • A Web page with a liquid layout changes its width when the browser window changes its width.
  • You learned how to create liquid layouts with and without whitespace.

What now?

Let’s see how you can create a new liquid layout for a site.

Liquid example

Where are we?

You’ve seen some liquid layouts. Let’s see how you would adapt what you’ve seen to create new layout.

This lesson’s goals

Learn:

  • To create a new layout, adapt something that already works.
  • Be careful when combining pieces to make a CSS selector. Commas and spaces are different.

Old dogs

Let’s create a liquid layout like this:

Old dogs

Figure 1. Old dogs

It has most of the usual regions: top, left, center and bottom. There is no right region. The bottom region is pushed to the right, to be under the center region.

The site will be about old dogs. The typeface is serifed, to give an older-style look. The colors are monochrome, consistent with that old theme.

The top and left regions have a thin dotted border. It’s gray as well, but a little darker than the background color. It’s a subtle effect.

The code

We’ll reuse the code we made on the previous page, for a liquid layout with spacing. It’s always a good idea to take something that already works, and customize it.

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>Old Dogs</title>
    <style type="text/css">
      * {
        margin: 0;
        padding: 0;
      }
      body {
        font-family: serif;
        font-size: 14px;
      }
      #top_region, #left_region {
        background-color: #F0F0F0;
        border: 1px dotted #D0D0D0;
      }
      #top_region {
        padding: 5px;
        margin: 5px;
      }
      #top_region #site_name {
        font-size: 36px;
      }
      #left_region {
        float: left;
        width: 80px;
        padding: 5px;
        margin: 0 5px 5px 5px;
      }
      #left_region .menu_item {
        padding-bottom: 10px;
      }
      #center_region {
        margin: 0 5px 5px 100px;
        padding: 5px;
      }
      #bottom_region {
        padding: 5px;
        margin: 0 5px 0 100px;
        border-top: 1px #AAAAAA solid;
        font-size: 10px;
      }
    </style>
  </head>
  <body>
    <div id="top_region">
      <p id="site_name">Old Dogs</p>
    </div>
    <div id="left_region">
      <p class="menu_item">Menu item</p>
      <p class="menu_item">Menu item</p>
      <p class="menu_item">Menu item</p>
      <p class="menu_item">Menu item</p>
    </div>
    <div id="center_region">
      <p>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.</p>
    </div>
    <div id="bottom_region">
      <p>Copyright © 2122</p>
    </div>
  </body>
</html>

Figure 2. The code

Look at the HTML first. Its structure is as before:

<div id="top_region">
...
</div>
<div id="left_region">
...
</div>
<div id="center_region">
...
</div>
<div id="bottom_region">
...
</div>

The CSS is where the magic happens. Look at this rule:

#top_region, #left_region {
   background-color: #F0F0F0;
   border: 1px dotted #D0D0D0;
}

The styles themselves are nothing new, but the selector is a little different. We want the top and left regions to have the same look. So we can combine them into a single rule.

Note the comma (,) in the selector. This makes the selector apply to both elements.

Here’s some more stuff:

#top_region #site_name {
   font-size: 36px;
}
...
<div id="top_region">
   <p id="site_name">Old Dogs</p>
</div>

site_name is contained in top_region. That’s why the selector works.

Note that there’s a space between the selector parts:

#top_region #site_name {

This tells the browser to look for site_name inside top_region.

So, when you use a comma, you select separate elements. When you use a space, you select contained (parent/child) elements.

Summary

  • To create a new layout, adapt something that already works.
  • Be careful when combining pieces to make a CSS selector. Commas and spaces are different.

What now?

Let’s look at fixed layouts, where pages stay the same size when the browser window is resized.

Fixed layouts

Where are we?

You know how a liquid layout works. You just saw how to create a new layout. Now let’s look at fixed layouts. Luckily, they’re almost the same as their liquid cousins.

What is a fixed layout?

A fixed layout stays the same width as the browser window is resized.

Fixed layout

Figure 1. Fixed layout

Typically, the page is centered on the screen. Extra space appears to the left and right of the fixed width page.

Fixed width designs are easier to control. You know exactly how much space there is in each column.

No whitespace

Let’s make this:

Fixed layout

Figure 2. Fixed layout

It’s zoomed out, of course. The content is centered in the browser window, with extra space on the left and right.

We can take the code for the fluid layout, and only change the CSS for the <body>. Here is the complete code, without whitespace:

<!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>Fixed layout</title>
    <style type="text/css">
      * {
        margin: 0;
        padding: 0;
      }
      body {
        font-family: Verdana, Helvetica, sans-serif;
        font-size: 14px;
        background-color: #ffeaff;
        width: 950px;
        margin: 5px auto 5px auto;
      }
      #top_region {
        background-color: #E0E0E0;
      }
      #left_region {
        float: left;
        width: 120px;
        background-color: #defee2;
      }
      #center_region {
        margin-left: 120px;
        margin-right: 120px;
        background-color: #fdffca;
      }
      #right_region {
        float: right;
        width: 120px;
        background-color: #ddddff;
      }
      #bottom_region {
        background-color: #E0E0E0;
      }
    </style>
  </head>
  <body>
    <div id="top_region">
      <p>Top region</p>
    </div>
    <div id="left_region">
      <p>Left region</p>
    </div>
    <div id="right_region">
      <p>Right region</p>
    </div>
    <div id="center_region">
      <p>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. </p>
    </div>
    <div id="bottom_region">
      <p>Bottom region</p>
    </div>
  </body>
</html>

Figure 3. Code for fixed layout

The CSS rule for the <body> tag in lines 11 to 17 has changed. Here’s the new rule:

body {
  font-family: Verdana, Helvetica, sans-serif;
  font-size: 14px;
  background-color: #ffeaff;
  width: 950px;
  margin: 5px auto 5px auto;
}

Figure 4. CSS rule for the <body> tag

You can try the page.

Line 14 gives the page background a (nasty) color, so you can see where the content begins and ends.

Line 15 sets the page’s width to 950px. Why 950? PC screen resolutions have some standard sizes, like 1,024px x 768px. Using 950px means that the page will fit on an 1,024px-wide screen. The extra 74px (1,024px – 950px) is for scroll bars, window borders, stuff like that.

As of January 2011, W3Schools reported that about 1% of their users had screen widths less than 1,024px.

The exception is mobile devices, which often use displays around 480px wide.

Line 16 centers the content on the screen. The line is:

margin: 5px auto 5px auto;

When you use auto for an element’s left and right margins, the browser centers the element. The element is the <body> in this case. The <body> contains everything, so the entire page is centered. W00f!

Whitespace

Earlier, you saw code for a liquid layout with whitespace between the regions.

Let’s create a fixed version of our test page. It will look like this:

Fixed with whitespace

Figure 5. Fixed layout with whitespace

It turns out to be quite easy. Just take the new CSS rule for the <body> from Figure 4, and plunk it into the code for the liquid layout with spacing. Here’s code for 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>Fixed layout with equal sidebar heights</title>
    <style type="text/css">
      body {
        font-family: Verdana, Helvetica, sans-serif;
        font-size: 14px;
        background-color: #ffeaff;
        width: 950px;
        margin: 5px auto 5px auto;
        padding: 0;
      }
      p {
        margin: 0;
        padding: 0;
      }
      #top_region {
        background-color: #E0E0E0;
        padding: 5px;
        margin: 5px;
      }
      #left_region {
        float: left;
        width: 120px;
        background-color: #defee2;
        padding: 5px;
        margin: 0 5px 5px 5px;
      }
      #center_region {
        margin: 0 140px 5px 140px;
        background-color: #fdffca;
        padding: 5px;
      }
      #right_region {
        float: right;
        width: 120px;
        background-color: #ddddff;
        padding: 5px;
        margin: 0 5px 5px 5px;
      }
      #bottom_region {
        background-color: #E0E0E0;
        padding: 5px;
        margin: 0 5px 0 5px;
      }
    </style>
  </head>
  <body>
    <div id="top_region">
      <p>Top region</p>
    </div>
    <div id="left_region">
      <p>Left region</p>
    </div>
    <div id="right_region">
      <p>Right region</p>
    </div>
    <div id="center_region">
      <p>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.</p>
    </div>
    <div id="bottom_region">
      <p>Bottom region</p>
    </div>
  </body>
</html>

Figure 6. Code for fixed layout with whitespace

You can try it. W00f!

Exercise: A fixed layout

Create a fixed layout like this:

Fixed layout

Figure 1. Fixed layout

This is zoomed out, of course. The actual width is 750px.

The top region uses the background color #6E9CF1. The text is white.

The right region uses the background color #F6F9FB. The top and bottom borders are dotted, with the color #DDDDDD.

The bottom region is centered. The top and bottom borders are dotted. The colors are #DDDDDD and #AAAAAA respectively.

(I based this design on the design Blue Freedom at Open Source Web Design.)

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

  • A page with a fixed layout maintains its width as the browser window changes size.
  • Creating a fixed layout requires just a small change in a liquid layout’s CSS.

What now?

You know how to make layouts like this:

Fixed with whitespace

Figure 5 (again). Fixed layout with whitespace

Maybe the page would look better if the sidebars and the center region were the same height.

Equal height sidebars

Where are we?

You know how to make fixed and liquid layouts. But there’s a problem we have to deal with.

This lesson’s goals

By the end of this lesson, you should know how make a layout’s regions have the same height.

The problem

Here’s a page using a liquid layout:

Unequal sidebar heights

Figure 1. Unequal sidebar heights

You can try it yourself. You’ll have to shrink the browser to make it look like Figure 1.

It looks OK, but the heights of the central area and the sidebars are unequal. It would be better if it looked like this:

Equal sidebar heights

Figure 2. Equal sidebar heights

You can try this one.

A solution

There is no simple way to make the heights equal in CSS.

But some jQuery code can do it. Rob Glazebrook figured it out, and made a plugin for it. I put the plugin at http://coredogs.com/resources/jquery.equalheights.js.

I changed the code a tiny bit to make it work better.

Run the plugin when the page loads. Tell it what regions you want to be equal height, and it will take care of the problem for you.

Here’s the code.

...
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://coredogs.com/resources/jquery.equalheights.js"></script>
<script type="text/javascript" language="javascript">
  $(document).ready(function() {
    $("#center_region, #left_region, #right_region").equalHeights();
  });
</script>
...
<div id="left_region">
...
</div>
<div id="right_region">
...
</div>
<div id="center_region">
...
</div>

Figure 3. Making the heights equal

Line 3 loads the plugin. It needs jQuery to run, so you need to load jQuery first (line 2). Line 6 runs when the page loads. Make a list of the regions you want to be equal, and then call equalHeights.

Exercise: Equal heights

Here’s a sad page. The column heights are broken. (You can download the code.)

Fix it.

Upload your solution to your server. Enter the URL.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

You know how make a layout’s regions have the same height. Run the equalHeights plugin when the page loads.

Exercises: Web page layout

You should do the recommended exercises. Do the optional exercises if you want more practice.

Recommended

Exercise: Dreamy

Check out the Dreamy template from OSWD.

I adjusted the template a little, made it simpler. You can see it.

Download a zip file with the HTML, CSS, and image files.

Use the template to make a site with animal jokes. Have a home page, a page for dog jokes, another for cat jokes, and another for horse jokes. Add other pages if you want. Remember to replace the placeholders in the template (title, slogan, etc.) with appropriate content.

In the right sidebar, add images of the appropriate animal. Use public domain or otherwise free images. There are links to free image sites on the links page.

Upload your site to your server, and put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Egyptian layout

Make a layout for a site about ancient Egypt. Put a header in the top region, a nav bar in the left region, and a footer in the bottom region.

Here are some background images that might be useful. They’re from GRSites.

Egyptian image

Egyptian image

Egyptian image

Also check out Webweaver and KingTutOne.

Upload your solution to your account. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Dog site layout

Make a Web site about fictional dogs. Here are the specs:

  • At least six pages.
  • Each page with the same layout.
  • The layout should be fixed, 750px wide, centered in browser’s window. There should be a header, a footer, a right region with a vertical nav bar, and a content area.
  • The header should have a tiled background. The header should have the same text and background on all pages.
  • The navigation bar should have buttons with an animated mouse-over effect. Every page should have the same buttons.
  • The footer should use a smaller font than the rest of the page.
  • Use sans serif fonts for everything.
  • Use a monochrome color scheme with a single accent color.

One of the pages should be a faux contact form. It should have fields for:

  • Name
  • Email address
  • Message

For each field, the label should be above the field. There should be a Send button. It should validate the comment field; there must be something in the comment field (show an error message if there is not. The other fields can be empty.

The form doesn’t actually have to send a message; it’s just pretend. But you should thank the user for sending a message, after s/he clicks the Send button.

Upload your solution to your hosting account. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Optional

Exercise: Computer layout

Make a layout for a site about computer electronics. Put a header in the top region, a nav bar in the right region, and a footer in the bottom region.

Here are some background images that might be useful. They’re from GRSites.

Computer image

Computer image

Computer image

Computer image

Computer image

Use other images if you want. Choose fonts and colors that fit.

Upload your solution to your account. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Change the blog design

Here’s the miniBLOG design from OSWD:

Original design

Figure 1. Original design

Download it, and change it to look like this:

New design

Figure 2. New design

These two images might be handy:

Logo

Body background

(This image is shrunk a little to make it fit. It’ll be bigger when you download it.)

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Reuse a design

Offbeat dog OK, I admit it. I have zero artistic skills. I can’t draw. There’s no way I could draw that offbeat dog on the right.

When I make a site from scratch, it ends up looking, well, not so good. My talents are in the geekery of the Web. Not in the art of it.

But some people are great at the visual side. Some of them share their work. Yay!

When I can, I use one of their designs. I prefer free designs, but will pay for one that does something I really need.

This chapter is about reusing designs. Usually, designs other people make don’t do exactly what you want. You need to change the graphics, colors, fonts, etc. I’ll show you how to do that.

Renata
Renata

Isn’t that cheating?

CC
CC

It sounds like stealing.

Renata
Renata

And why did we bother learning all that stuff in the other chapters? We’re just going to use an existing design.

Kieran
Kieran

Good questions.

Only use designs you have the right to. The people who made them gave us permission to use the designs. There are plenty of good, free designs out there. Plus lots of low-cost paid designs.

Professional Web developers often reuse designs. This isn’t cheating. It’s good business. It saves time and money.

Now, about the learning. You can’t reuse designs unless you can make them do what you want. You need to know about images, links, nav bars, tables, layout… stuff we’ve already talked about.

CC
CC

Do you reuse designs from other people?

Kieran
Kieran

Yes! I didn’t make the CoreDogs theme from scratch. I based it on the design Nonzero.

What you’re going to learn is legitimate. As long as you abide by the design’s terms of use, or license. We’ll talk about licenses soon.

Let’s start by looking at the goal. At the end of the reuse process, what do we want to have?

The goal

This lesson’s goals

By the end of this lesson, you should:

  • Know what the terms layout, design, and template mean.
  • Know how a template gets reused.
  • Be able to list the things you need to do to reuse a design.

Some terms

Let’s define some words, so we know what we’re talking about.

  • Layout. You already know this one. The regions on a page, and what they’re used for.
  • Template. An HTML file containing all the standard elements on a page, like headings and nav bars.
  • Design. A template and the complete set of files it uses, including CSS, JavaScript, and image files.

Let’s use an example to see how the three relate.

A layout

You learned about layouts in the last chapter. On most Web sites, pages use the same regions for the same things. For example, on every CoreDogs lesson page, there’s a lesson menu on the right.

A layout standardizes the way a site uses page regions. Here’s an example:

Standard layout

Figure 1. Standard layout

The header extends over both the content and the nav bar. The footer extends under both of them.

The layout doesn’t give any content. It doesn’t give formatting, either. For example, the footer might have a solid border and background color, or no border or background color.

There can be more than one layout for a site. For example, most of the pages on a site might use the layout in Figure 1. But pages in the Photo Gallery might use this layout:

Image gallery layout

Figure 2. Image gallery layout

A template

A template is an HTML file for a layout, with empty slots where content goes. You copy a template for each page on a site.

Here’s part of a template:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
...
    <title>[Site name]</title>
...
    <link rel="stylesheet" type="text/css" href="gorotron2.css"/>
...
          <h1>[Site name]</h1>
          <h2>[Subtitle]</h2>
...
        <h3>[Heading]</h3>
        <p>
          Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
        </p>
        <p>
          Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
        </p>
        <h3>[Heading]</h3>
        <p>
          Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
        </p>
...
</html>

Figure 3. Part of a template

Lines 4, 8, 9, 11, and 18 have spaces for text to go. The lorem ipsum text is just filler.

Let’s say the file in Figure 3 is called template.html. To make the home page for your site, you copy template.html, and name the copy index.html. You fill in the empty slots.

To make a contact page, you copy template.html, and name the copy contact.html. You fill in the empty slots.

And so on.

Here’s line 6 of the template:

   <link rel="stylesheet" type="text/css" href="gorotron2.css">

Why do I point this out? Because of …

A design

A design is one or more template files, plus the CSS files, image files, and JavaScript files that the template(s) use.

Here’s how the template in Figure 3 renders, when it has all of the files it needs:

Rendered template

Figure 4. Rendered template

This is based on the Random Landscapes design.

To sum up, here are those terms again:

  • Layout – regions on a page.
  • Template – an HTML file containing all the standard elements on a page, like headings and nav bars.
  • Design – one or more templates and the complete set of files they use, including CSS, JavaScript, and image files.

Start and end points

Here’s what happens when you reuse a design.

Start: A design that someone else made. The person who made the design had their own goals. They probably don’t match your goals, not exactly. So you need to change the design.

End: You have a new design, one that does what you want. Maybe the layout’s been changed, there are new colors, new fonts, whatever.

The new design has a template (maybe more than one). The template is based on the code on the original design, but changed to meet your requirements.

So you have one or more templates. You copy the template(s) to make your site.

How do you reuse a design?

Say you want to make a new site. You decide to reuse a design. Here’s what you do.

  • Decide what your site should look like. Layout, mood, etc.
  • Find a design. Look through what’s out there, and pick something.
  • Gather your tools. Browser, editor, graphics program, and other stuff.
  • Set up your working directories. Keep copies of your work in stages. If you mess up, you can go back to the last checkpoint.
  • Make new templates. Change the layout, fonts, and graphics.

Summary

  • A layout is the regions on a page.
  • A template is an HTML file you copy and complete.
  • A design is one or more templates and their supporting files.
  • To reuse a design:
    • Decide on what your final site should look like.
    • Find a design.
    • Gather your tools.
    • Set up your directories.
    • Make new templates.

What now?

Let’s find a design, and reuse it.

Getting ready

Where are we?

You’ve decided to create a new site by reusing an existing design. Now what?

This lesson’s goals

See how to:

  • Work out what you want.
  • Gather your tools.
  • Set up directories.

Knowing what you want – a little

You’ll be looking at lots of different designs. How do you know what to choose?

Making a list of things the design must have. Such as:

  • Mood. Modern, traditional, fun, conservative, extreme, decorative, plain…
  • Layout.
    • How many side bars?
    • Menu location – left, right, top, whatever.
    • Want a footer?
    • Place for a logo in the header?

When you’re making your must-have list, don’t be too picky. You may not find a design that’s exactly what you want.

If you’re making a site for young girls, don’t say: “The design must have a pink background with flower accent graphics.” You probably won’t find it.

Instead, say: “The design should be attractive to young girls.” That’s the right goal, and you’ll have more options to choose from.

Renata
Renata

I see some Flash templates out there. You can make a complete Flash site. What do you think?

Kieran
Kieran

I’d avoid that. Flash is great, but not for entire sites, unless you have very good reasons.

First, you need special tools to edit Flash. Some template companies offer online tools that make it easy to make a Flash site. But if you want to do something even a little bit different from what their tools do, you’re out of luck.

Second, Flash sites don’t index well with search engines. If search engine traffic is important to you, don’t use Flash.

Third, Flash sites can be just plain annoying. They’re cool when you first see them. But after a while they can be painful.

CC
CC

Does Flash have any place?

Kieran
Kieran

Yes! Slide shows with voice over, educational animations, games… I’ve done a lot with it over the years, and still use it. Just not for entire sites.

Gather your tools

Here’s a basic toolkit. Everything is free. You’ve seen this stuff before. I just want to remind you.

  • NetBeans or another IDE. For editing HTML, CSS, and JavaScript.
  • Firefox. The official CoreDogs browser.
  • Firebug. A Firefox extension. Lets you find the right CSS to change.
  • ColorZilla. Another Firefox extension. Lets you get the right color codes.
  • MeasureIt. Yet another Firefox extension. Lets you make things the right size.
  • Paint.NET or another graphics program. Make and change graphics. I use Paint.NET for simple things, and Gimp for more complex tasks.
  • WinSCP or another file transfer program. To get your work up to the server.

Set up your development directories

You’ll need to have a directory on your hard disk (or USB flash drive or whatever) to do your work. For example, if you’re working on a site called BiteSize, you might open your Documents directory, and make a directory called BiteSize.

Project directory

Figure 1. Project directory

When you work on a design, make snapshots as you go. A snapshot is a copy of the design at a point in time. If you mess something up, you can go back to the last snapshot.

When to make a snapshot? When you’ve got part of the design working. Say the first thing you work on is the top nav bar. When you get it right, take a snapshot. Then you work on the layout. When you get that right, take a snapshot. And so on.

How to make snaphots? First, make a subdirectory in BiteSize called current. This is where you do your work. After you’ve been working for a while, make a copy of current, and call it snapshot1. Keep working. When you’ve made a bunch o’ new changes, copy current again, and call it snapshot2. And so on.

After a while, your working directory will look like this:

Project directory with snapshots

Figure 2. Project directory with snapshots

snapshot1 would be the oldest snapshot. snapshot4 would be the newest snapshot. current would be your most recent work.

Suppose you made a bunch of changes to current, and they weren’t working. You’ve lost track of what you did. You’d rather just start this part over. You can delete current, copy snapshot4, and rename the copy to current.

What you’re doing is called “version control.” This simple approach is just fine for basic, one-person projects. Professionals working in teams use version control software, like Git.

Summary

  • Work out what you want, but only in general terms. Be open to new ideas as you look at designs.
  • Get your tools ready. IDE, browser, extensions, graphics editor, and file transfer tool.
  • Make working directories.

What now?

Let’s go find ourselves a design!

Find a design

Where are we?

We’re going to make a site, reusing an existing design. We’ve gathered the tools we need. Now for the next step.

This lesson’s goals

By the end of this lesson, you should:

  • Know how to find a design.
  • Be able to check the design’s license.
  • Know what to look for in the design’s code.
  • Know how to find elements with Firebug.
  • Be able to finish setting up your work area.
  • Know how to create a NetBeans project.
  • Know how to strip out unneeded content.
  • Be able to convert an XHTML file to HTML.

Find a design that meets your goals

Let’s work on an example. Here’s my friend Giles.

Hey, everybody

He’s into poetry. Likes to collect it, and read it to people. He’s really into poetry about nature.

Sure am

What can I do for you?

Can you make me a site?

Sure. What should it be like? Features, look, feel, like that.

Green, links to poems, an about me page, and a contact page.

OK, let’s see what I can do. I’ll look around for a design I can adapt. You can tell me what you think.

Okey dokey

I’ll start at Metamorphosis Design. They have hundreds of free templates. Let me see…

Found another template site you like? Add it to the links page.

Clock (Tick tock)
(Tick tock)
(Tick tock)

Here’s a design that might work. It’s called Metamorph Hills. What do you think?

Changes

I should be able to do that.

But I’m not sure whether we can use the design yet. I need to check a couple of things.

Exercise: Find free designs

Find at least five sites that offer designs for free. Enter their URLs.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Check the license

I need to check what I’m allowed to use the design for. The license will tell me. There are many kinds of licenses. Common ones are:

  • Public domain. Anyone can use the design for free, including commercial use.
  • Creative commons. Several variants with different permissions. For example, a design with a CC license might be free for commercial use, or not. The designer will tell you.
  • Commercial, non-exclusive. You can buy a license to use the design. Other people can buy a license to use the same design.
  • Commercial, exclusive. You buy the right to be the only person who can use the design.

Make sure you can accept designers’ terms before you use their work. If you’re looking for free stuff, public domain and Creative Commons usually work best. Remember, some Creative Commons licenses allow free commercial use. Others do not.

The license for Metamorph Hills is:

This website template is released under a Creative Commons Attribution 2.5 License.

We request you retain the full copyright notice below including the link to www.metamorphozis.com.

...

You are allowed to use this design only if you agree to the following conditions:

- You cannot remove copyright notice from this design without our permission.

- If you modify this design it still should contain copyright because it is based on our work.

- You may copy, distribute, modify, etc. this template as long as link to our website remains untouched.

I can live with that. I just need to leave the link to www.metamorphozis.com in the footer.

CC
CC

I don’t get it. Why would Metamorphosis Design let us use their work for free? Nobody is going to see the link down there.

Kieran
Kieran

You’re right, not many people will read the footer. But each time someone links to a page, that page gets a little more Google juice. This boosts Metamorphosis Design’s ratings for Google searches like “Web templates.”

Exercise: Check the licenses

Find three designs, with different licenses:

  • A public domain design.
  • A creative commons design that cannot be used for free for commercial purposes.
  • A creative commons design that can be used for free for commercial purposes.

For each one, enter:

  • The design’s URL.
  • A copy of the design’s license (the text that says what you can and cannot do with the design).

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Check the code

I always go through a design’s code before I commit to using it. What am I looking for?

Easy to understand

Here’s something that is very important:

The code must be easy to understand.

After you download a design, look at the HTML and CSS. Good designers write simple, easy-to-understand code. See if you can match the code in the HTML file to different parts of the layout. If you can’t, consider using another design.

What did I do for Giles’ site? I downloaded the zip file that Metamorphosis Design provides, and extracted the files. Then I went through the HTML, to see if I could match the code up with the main pieces of the page. Here’s the rendered page, shrunk to fit:

Rendered

Figure 1. Rendered page

Here’s some of the HTML:

<body>
  <div id="menu">
    ...
  </div> 
  <div id="content">
    <div id="header">    
      <div id="logo">
        ...
      </div>
    </div>
    <div id="main">
      <div id="right">
        ...				
      </div>
      <div id="left">		
        <h3>Nunc pellentesque</h3>
        ...
      </div>
    </div>
    <div id="footer">
      <p>Copyright © 2008...</p>
    </div>
  </div>
</body>

Figure 2. Template HTML

Let’s see if we can match them up.

The <body> is divided into two containers: menu (lines 2 to 4) and content (lines 5 to 23). Here’s what they correspond to on the page:

Main containers

Figure 3. Main containers

It didn’t have to be done this way, but it was. It works, so there’s no need to change it.

menu is obviously the top menu. Let’s look at the other container – content – and see how it works. Here’s the code:

  <div id="content">
    <div id="header">    
      <div id="logo">
        ...
      </div>
    </div>
    <div id="main">
      <div id="right">
        ...				
      </div>
      <div id="left">		
        <h3>Nunc pellentesque</h3>
        ...
      </div>
    </div>
    <div id="footer">
      <p>Copyright © 2008...</p>
    </div>
  </div>

Figure 4. Part of the template HTML

content has three containers: header (lines 6 to 10), main (lines 11 to 19), and footer (lines 20 to 22). Here they are on the page:

Containers in the content container

Figure 5. Containers in the content container

header doesn’t have much in it. Just a place for a logo and stuff.

main has some important containers. Here’s the code:

    <div id="main">
      <div id="right">
        ...				
      </div>
      <div id="left">		
        <h3>Nunc pellentesque</h3>
        ...
      </div>
    </div>

Figure 6. Part of a part of the template HTML

Here are the containers in the main container:

left and right inside main

Figure 7. left and right inside main

OK, I can figure out which piece of the page is created by which part of the HTML code. Why does this matter? Because if I don’t understand the code, I can’t change the look.

The CSS is straightforward as well. Here’s part of it:

#left {
  width: 220px;
  margin-left: 20px;
}
#right {
  width: 510px;
  float: right;
  padding-right: 20px;
}

Figure 8. Part of the CSS

These two rules style the left and right containers inside main. Line 2 sets the width of left to a narrow 220 pixels. Line 3 moves left 20 pixels in from the left edge of its container, main.

There’s something important there. left is inside main in the HTML:

    <div id="main">
      <div id="right">
        ...				
      </div>
      <div id="left">		
        <h3>Nunc pellentesque</h3>
        ...
      </div>
    </div>

Figure 6 (again). Part of a part of the template HTML

So main is positioned first, and then left is positioned inside main. What about right? It’s inside main to