Events

See more about:

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

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

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

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.


How to...

Lessons

User login

Log in problems? Try here


Dogs