Writing a JS program
This page’s goals
On this page, you’ll learn how to:
- Plan your JavaScript program.
- Associate events with code.
- Show and hide page elements.
Planning your program
Here are the steps involved in writing a simple program.
- Know what you want.
- Identify events.
- Name things.
- Attach code to events.
Know what you want
The most important step is knowing what you want your program to do. This is also often the hardest thing to get right.
If you aren’t careful, you can spend a lot of time solving the wrong problem. This is a Big Issue in the business world. For example, a car company might spend millions of dollars designing a car that nobody wants.
One way to work out what you want is to write down different states that you want your Web page to be in.
Let’s take an example. Suppose you want users to fill in a form on your Web site. You want to give instructions for filling out the form, but you want to let users hide the instructions if they want. This will help experienced users.
You decide to write a program that will show instructions if the user clicks on “Show instructions.” Your program will also let users hide the instructions.
Your Web page will be in two different states:
- Instructions hidden
- Instructions showing
You might draw the states on paper, like this:

Figure 1. Planning states
I know, my paw-writing is terrible. I grew up in the southern hemisphere, but live in the northern. Ink and graphite molecules work differently up here.
At least, that’s my excuse.
The differences are at (1) and (2). At (1), the message is “Show instructions” and the instructions are hidden. At (2), the message is “Hide instructions” and the instructions are showing.
Identify events
We have two states. What triggers a change between the two states? An event, that’s what. An event is something that happens on a Web page.
We’ll only talk about two events for now:
click()
ready()
A click() happens when – you guessed it – someone clicks on something.
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. That is, in the ready() event, you bind code to events.
Name things
So far, you’ve worked out what your program will do, and you’ve identified events that you 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 2. The id attribute
An attribute is something you attach to an HTML tag, that modifies it in some way. There are many different attributes, and we’ll see them later. For now, the only one we are 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 code. In our example, we need to mess with two things:
- The instructions title that changes between “Show instructions” and “Hide instructions.”
- The instructions, which are visible or not.
So we’ll give ids to these two things.
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
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
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.
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:

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.)
Other things
There are two other things we’d need to do to make this example actually useful.
- Change
instructions_titleback toShow instructions von every other click.
- Use up and down arrows rather than v and ^.
You’ll learn how to do all of these 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.