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.
CoreDogs does something similar. Here’s an example.
Figure 1. Showing help
This is more-or-less what we want to do. But we’ll make it simpler. Have a look at this page. Click on “Show instructions” and see what happens. (The “v” represents an image of a down arrow.)
This is what we want to end up with.
A good way to get started is to write down:
- The states we want the Web page to be in.
- The events that trigger state transitions.
Argh!! Big words!
Calm down. They’re big words for simple things. Don’t switch off. It will all make sense.
A state is the way something is at a point in time. For example:
- 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:

Figure 2. 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 text. State transition diagrams show the events that trigger state changes. What causes the page from move from one state to another.
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. It uses the states from Figure 2.

Figure 3. 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.
Exercise: States and transitions
Here’s a story.
This is Billy. He was walking along one day. Nice and calm, just out for a walk. Suddenly, he saw a rabbit. Wow! He got so excited! Bark, bark! The rabbit ran away.
Billy calmed down, and kept walking. Then he saw something very strange. It was a dude on a pogo stick. Billy had never seen one of them before, and he didn’t know what to make of it. He was frightened, so he hid, until the dude on the pogo stick went away.
Billy calmed down again. He finished his walk, and took a nap.
Two things:
- List the states that Billy was in. Don’t worry about the other characters.
- Draw a state transition diagram.
You don’t know how to put pictures on the Web yet. One way to draw the diagram is with text. It’s a pain, but the diagram for Billy’s walk is simple enough.
Here’s an example of what I would type in the exercise solution field to make a drawing:
<pre> State 1 <-- | | | | Event A Event B | | v | State 2 --- | | Event C | v State 3 </pre>
Here’s a screen shot of me typing it in:

It looks like this when I’m done:

You can see my solution, but do it yourself first!
(Log in to enter your solution to this exercise.)
Events, states, and JavaScript
So, a Web page is on the screen. There’s an event, like a click. Something changes the page to a new state.
In our form help example, something waits for a click. When it gets the click, something shows the help. When there’s another click, something hides the help. When there’s another click, something shows the help. Try the page again. Something changes the help message’s visibility.
What is the something that changes the page? It’s the browser itself. The browser knows how to hide things, and show things.
How does the browser know that it should show the help when a user clicks on “Show help v”? It doesn’t. You have to tell the browser what to do.
Here are two programs. They’re not in JavaScript, just English. But I want you to understand the concept.

Figure 4. Two programs
Each program is just a single line. That’s OK. Programs can be any length.
We want the browser to run the first program when the user clicks on “Show help v.” We want the browser to run the second program when the user clicks on “Hide help ^.” Here’s how we would put them together.

Figure 5. Two programs again
Each event wraps a program. When the event happens, the program runs. These two pieces of code are called event handlers.
Here’s the general template for that:

Figure 6. Event template
All programs run this way (as far as we are concerned).
You can make the program do anything you can tell the browser to do. You can tell it to create things, erase things, hide things, show things, change the text of paragraphs, headings and other things, show popup messages to the user, ... lots of stuff.
Here’s an unfriendly program.

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

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

Figure 6 (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. To see why, you need to understand the problem this event solves.
There are thousands of possible events that can happen on a typical Web 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. And that’s just the click event. There are many other events, like the mouse going over an element, the mouse leaving an element, a key being typed, etc.
The browser doesn’t watch for all possible events. Instead, we tell it what events to watch for. Here are the event handlers again:

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

Figure 9. 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
Let’s write the HTML for the page. Remember that 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 10. HTML
You can see the HTML objects the program will mess with: the help prompts that people will click on (lines 2 and 3), and the help message that will be shown and hidden (lines 4 to 6). You can see the page as it is so far.
How come I can see both help prompts?
We’ll change it in a moment, so that the user will see only one or the other.
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 11. 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 12. Giving HTML elements ids
There are four <p> tags, but only two have ids. Why?
We only need to attach ids to HTML elements we refer to in JavaScript code. We’ll attach code to “Show instructions” and “Hide instructions,” so they need ids. So do the instructions themselves, because they will be hidden and shown.
But our program doesn’t do anything with the first <p> tag. No events are attached to it, and our program doesn’t change it in any way. So, no need for an id.
So if you don’t need to, don’t attach an id?
Right. Sometimes you give HTML elements ids so you can style them with CSS, and that’s OK. But unless an HTML element is being used by JavaScript or needs to be styled by CSS, don’t give it an id.
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 13. 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 14. Hiding instructions
Remember, everything between $(document).ready(function() { and }); runs once the page has been loaded.
The $("#instructions") in line 3 tells jQuery to find some elements on the page. Which ones? The ones that have an id of instructions. Be sure to include the #. This is what tells jQuery to look at the id attribute, and not some other attribute. Leaving out the # is a common error.
There should be only one element with an id of instructions. If there is more than one, browsers can start acting strangely.
The rest of the statement tells jQuery what to do with the elements it finds. .hide() tells jQuery to hide them.
In English, $("#instructions").hide(); is:
Find all the elements with an
idofinstructions, and hide them.
The ; at the end of the line tells JS that this is the end of the statement. It’s optional, but good practice.
You can try the page so far.
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 15. 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 16. 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.
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 help prompt
We’re almost done.
Right now, we have both help prompts showing:

Figure 17. 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>
Figure 18. Prompt visibility
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 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 19. Styling the cursor
There are several new things here. First, there’s the # in front of the selectors. This is same thing that jQuery uses. #instructions_title_show means “find the thing with the id of instructions_title_show, and apply the style.” In fact, jQuery borrowed this syntax from CSS.
The second new thing is the :hover. This is called a pseudo-class. :hover means “apply the styles when the mouse is on the element.” You can apply any styles at all. You can change the font, color, background color, whatever. For example, you could do this:
<style type="text/css">
#instructions_title_show:hover {
cursor: pointer;
font-weight: bold;
font-size: 24px;
color: red;
background-color: yellow;
}
</style>
Figure 20. 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 19 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 21. Heading styles
Make sure you use a comma (,) to separate the items. If you leave it out, the rule won’t work.
Wow, that took a long time. For such a simple program.
Only because this was our first program. Every program we write will use events and such in the same way. So we won’t have to go as slowly.
Exercise: Tell a dog joke
Write a program to show the first part of a dog joke:

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

You can see my solution. Don’t look at the source code until you’ve tried it yourself!
Upload you solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
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.
This is Billy. He was walking along one day. Nice and calm, just out for a walk. Suddenly, he saw a rabbit. Wow! He got so excited! Bark, bark! The rabbit ran away. 



