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?