Changing text

See more about:

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

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

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.


How to...

Lessons

User login

Log in problems? Try here


Dogs