Writing a JS program

This page’s goals

On this page, you’ll learn how to:

  • Plan a JavaScript program.
  • Associate events with code.
  • Show and hide page elements.

Planning your program

Here are the steps involved in writing a simple program.

  • Work out what you want your program to do.
  • Write the HTML your program will work with.
  • Name things.
  • Attach code to events.

Work out what you want

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

You can see the final page. Click on “Show instructions” and see what happens. (The “v” represents an image of a down arrow.)

A good way to get started is to write down:

  • The states we want your Web page to be in.
  • The events that trigger state transitions.
CC
CC

Argh!! Big words!

Kieran
Kieran

Calm down. They’re big words for simple things. Don’t switch off. It will all make sense.

A state is the way something is at a point in time. For example:

  • At midnight you are in the “sleep” state. At noon, you are in the “wake” state.
  • Before you see a squirrel, you and the squirrel are in the “calm” state. After you see the squirrel, you are in the “excited” state, and the squirrel is in the “frightened” state.

Events cause changes between states. The alarm clock triggers a change between the sleep and wake states. Seeing a squirrel causes changes in your state and the squirrel’s state.

The Web page for our example will be in two different states:

  • Instructions hidden
  • Instructions showing

It helps to draw the states on paper, like this:

Planning states

Figure 1. Planning states

In the “Instructions hidden” state, the help prompt is “Show instructions” with a down arrow, and the instructions are hidden. In the “Instructions showing” state, the message is “Hide instructions” with an up arrow, and the instructions are showing.

So that’s the states. The various ways the Web page can look.

Identify events

Recall that events are things that happen, like users clicking on things. State transition diagrams show the events that trigger state changes.

Oooo… “state transition diagrams” sounds so geeky and cool. Impress your friends.

Friend: Hey, what are you doing?

You: Working on a state transition diagram. It’s a programming thing.

Friend: Oh. (Walks away, thinking you must be über smart.)

Here’s a state transition diagram for this program:

State transition diagram

Figure 2. State transition diagram

A click on the help prompt (Show instructions or Hide instructions) moves to the other state.

OK, so it’s not complicated. But “state transition diagram” still sounds impressive. Just don’t use the acronym STD. That means something else.

jQuery has a click() event. We can use that.

There’s one other jQuery event we’ll need: ready(). A ready() event happens just after a Web page has finished loading. Usually you put initialization code in the ready() event. That’s code that runs once, to finish getting the page ready for the user.

In jQuery, one of the things that the ready() event does is set up the other events. There are thousands of possible events that can happen on a particular page. For example, you could let the user click on every different character on the page – every a, b, c, 1, 2, 3, ... – and run some code.

Rather than having the browser watch for every possible click() event, you tell jQuery which events you want it to watch for. You do this in the ready() event, the first thing triggered when the page is shown.

Write the HTML your program will work with

What I normally do at this stage is write the HTML I need. Remember that most JavaScript code messes with HTML objects, like paragraphs.

Here’s some HTML for this example:

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

Figure 3. HTML

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

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 4. The id attribute

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

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

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

Once we’ve given an element an id, we can mess with i. In our example, we need to mess with two things:

  • 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 5. 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.

Let’s begin by creating the page that we’re going to attach code to.

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

Figure 3. Starting out

I’ve included all the things that will show on the page eventually, even if they’re not shown when the page is first display. For example, the instructions are not shown when the page is first displayed. But they will be.

Note that I’ve loaded jQuery.

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

I’ll start this program by hiding the instructions when the page loads. This code goes into the head. Or somewhere.

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

Figure 4. Hiding instructions

Everything between $(document).ready(function() { and }); runs once the page has been loaded. Don’t worry about why it looks like this. Just copy-and-paste these two lines, and know that it works.

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

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

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

In English, the statement is:

Find all the elements with an 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

I could write the rest of program in one step, but I won’t. I’ll just see if I get the event binding to work. Remember that this ties some code to an event.

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

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

Figure 5. Eventing

You can try it.

Notice that the event binding is done within the ready() event. Remember that ready() runs after the page has been loaded. This makes sure that the element the code is bound to exists before the binding is attempted.

$("#instructions_title") means “find everything with an id of instructions_title.” There is only one thing with that id. .click(function() { means “Here’s what to do with the user clicks on it.” You can just copy-and-paste this, along with the }); that closes the event code.

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

Toggling visibility

For the next step, I’ll do this:

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

Figure 6. Toggling visibility

You should try it.

$("#instructions") means “Find everything with an id of instructions. .toggle('slow') means “Toggle its visibility.” If it’s showing, hide it. If it’s hidden, show it. 'slow' means to do it slowly – which is still kind of fast in jQuery. You can use 'medium' or 'fast' as well or leave it out, which would be .toggle().

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

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.

Here’s my solution. Don’t look at the source code until you’re tried it yourself!

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

Changing the title

I’ll add one line.

<script type="text/javascript">
  $(document).ready(function() {
    $("#instructions").hide();
    $("#instructions_title").click(function() {
      $("#instructions_title").text("Hide instructions ^");
      $("#instructions").toggle('slow');
    });
  });
</script>

Figure 7. Changing instructions

$("#instructions_title") says “Find everything with an id of instructions_title.” .text("Hide instructions ^") says “Replace the text with Hide instructions ^.” So this actually changes the content on the page.

Try it.

Exercise: Secret of a happy life 2

Change your secret program so that when the user clicks on secret_instructions, its text changes to “The secret is:”

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

Here’s my solution. Don’t look at the source code until you’re tried it yourself!

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

A better mouse cursor

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

I added the following to the page:

<style type="text/css">
  #instructions_title:hover {
    cursor: pointer;
  }
</style>

Figure 8. Styling the cursor

There are three new things here. First, there’s the # in front of the selector. This is same thing that jQuery uses. #instructions_title means “find the thing with the id of instructions_title. In fact, jQuery borrowed this syntax from CSS.

What this means is that the styles in the { } will be applied only to instructions_title.

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

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

Figure 9. Going too far

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

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

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

You can see my solution. Don’t look at the source code until you’ve tried it yourself!

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

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

Other things

There are two other things we’d need to do to make this example actually useful.

  • Change instructions_title back to Show instructions v on every other click.
  • Use up and down arrows rather than v and ^.

You’ll learn how to do these things later.

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.
  • Change the text of an element.

All cool stuff!

What now?

Let’s get some data from the user and do stuff with it.