Changing images - jQuery and the if statement

See more about:

Where are we?

You know how to show an image on an HTML page. But the image doesn’t have to just sit there. You can hide images, show them, change their size, and other stuff.

This page’s goals

By the end of this page, you should:

  • Be able to show and hide images based on events.
  • Understand how a basic if statement works.

Review: Showing and hiding text

In the previous chapter (A Web page that interacts), you learned how to use JavaScript to show and hide text. Let’s look at an example to refresh your memory.

Let’s create a Web page with a dog riddle. The question is shown to start with:

Dog joke start

Figure 1. Dog joke start

Click the text that says “Click to show/hide the answer,” and you see:

Dog joke answer

Figure 2. Dog joke answer

You can try the page.

Here’s the 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">
    <title>Dog Joke</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#answer").hide();
        $("#toggle_answer").click(function() {
          $("#answer").toggle('slow');
        });
      });
    </script>
  </head>
  <body>
    <h1>A Dog Joke</h1>
    <p>What do you get if you cross a Red Setter with a Pointer?</p>
    <p id="toggle_answer">Click to show/hide the answer</p>
    <blockquote id="answer">A Pointsetter, the Christmas dog.</blockquote>
  </body>
</html>

Figure 3. Dog joke code

Remember that an event is something that happens. The ready() event happens when a page has been loaded. Lines 9 to 12 are run when the page has been loaded, but just before it is shown to the user.

Line 9 hides the answer to the riddle. Lines 10 to 12 set up the the click() event for the thing with the id of toggle_answer (don’t forget the # to tell the browser to look at the id attribute). When toggle_answer is clicked, toggle the visibility of the thing with the id of answer.

Showing and hiding an image

You can do the same thing with an image. Let’s create a page with a button on it that shows and hides a picture of a puppy. It will start like this:

Show puppy start

Figure 4. Show puppy start

Click the button, and you see:

Show puppy start

Figure 5. Show puppy end

You can try the page.

Here’s the 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">
    <title>Cute Puppy</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#puppy_container").hide();
        $("#show_hide_puppy").click(function() {
          $("#puppy_container").toggle('slow');
        });
      });
    </script>
  </head>
  <body>
    <h1>A Cute Puppy</h1>
    <p><button id="show_hide_puppy" type="button">Show/hide puppy</button></p>
    <p id="puppy_container"><img src="renata_young.jpg" alt="Cute puppy"></p>
  </body>
</html>

Figure 6. Show puppy code

The JavaScript is the same as before. The only thing that’s changed is the object that’s being shown and hidden. It’s puppy_container.

Note how I named it. puppy_container is a <p> tag that contains the <img> tag that shows the image.

Exercise: Show and hide a drawing

Here’s a drawing:

Yummie

Create an HTML page with a button that shows and hides the drawing.

Upload to your server. Put the URL below.

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

Changing the button caption

For our next trick, let’s change the button’s caption in the puppy show program. The button says “Show/hide puppy.” Let’s make it say “Show puppy” or “Hide puppy,” depending on whether the photo is showing or not.

The page will start like this:

Show puppy, simpler button

Figure 7. Show puppy, simpler button

Press the button, and get:

Nice puppy!

Figure 8. Nice puppy!

You can try the page.

Notice that the text on the button has changed. So, both the image and the caption switch back and forth between two states. When the image is not showing, the caption says “Show puppy.” When the image is showing, the button says “Hide puppy.” When the user clicks the button, both the image and the button change.

To show and hide an image, there’s the handy toggle() function. Toggle does some work for us. If the thing being toggled is showing, toggle() hides it, and vice versa.

There is no built-in function for toggling button captions. We have to handle the change ourselves.

First, I’ll work out the logic. I’ll write pseudocode.

When the button is clicked:
  Get the button caption
  If the caption is "Show puppy"
    Make the caption say "Hide puppy"
  If the caption is "Hide puppy"
    Make the caption say "Show puppy"
  Toggle the image

Figure 9. Pseudocode for the button click

Click the button, then click again, then click again, then click again, and the button’s caption will go back and forth between “Show puppy” and “Hide puppy.”

Let’s write it in 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">
    <title>Cute Puppy</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#puppy_container").hide();
        $("#show_hide_puppy").click(function() {
          var button_caption = $("#show_hide_puppy").text();
          if ( button_caption == "Show puppy") {
            $("#show_hide_puppy").text("Hide puppy");
          }
          else {
            $("#show_hide_puppy").text("Show puppy");
          }
          $("#puppy_container").toggle('slow');
        });
      });
    </script>
  </head>
  <body>
    <h1>A Cute Puppy</h1>
    <p><button id="show_hide_puppy" type="button">Show puppy</button></p>
    <p id="puppy_container"><img src="renata_young.jpg" alt="Cute puppy"></p>
  </body>
</html>

Figure 10. Toggling the button’s caption

Getting text

Line 11 is:

var button_caption = $("#show_hide_puppy").text();

This will get the current value of the button caption, and put it into the variable button_caption. Then we can test it.

This is a different use of the text() function. Earlier, we used text() to set the text in something, like this:

$("#best_color").text("Green")

This put the text Green into the thing with the id best_color.

You can also use text() to get the text in something. That’s what happening in line 11. Leave the parenthesis (that is, the () ) empty, and jQuery will return the text that’s already in the object.

Several jQuery functions are like this. We’ll see more of them later.

Testing stuff

Line 12 introduces the if statement. The if statement lets browsers make decisions, doing different things depending on the circumstances.

The if statement only has two possibilities. It does one thing, or the other, and that’s it. Other statements let you have more than two options, but that’s for a future lesson.

The if statement looks like this:

if ( test ) {
  stuff to do if test is true
}
else {
  stuff to do if test is false
}

Figure 11. Iffy if, the ifster

The test is usually a comparison of some sort. The == in line 12 means “is equal to.” It’s true when the things on either side of the == are the same. Otherwise, it’s false.

Don’t confuse = and ==. They’re different. = means “put the thing on the right into the variable on the left.” == means “compare the things on the right and left.”

Back to the example.

var button_caption = $("#show_hide_puppy").text();
if ( button_caption == "Show puppy") {
  $("#show_hide_puppy").text("Hide puppy");
}
else {
  $("#show_hide_puppy").text("Show puppy");
}

(Part of) Figure 10 (again). Toggling the button’s caption

So line 12 says,

Is the variable button_caption equal to Show puppy?

If it is, the browser runs line 13, setting the button’s text to Hide puppy. If it isn’t, the browser runs line 16, setting the button’s text to Show puppy.

Exercise: Caption update

You wrote a page to show and hide a pretzel. Update it so that it changes the button’s caption appropriately.

Upload your file to the server. Put the URL below.

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

Now try this one.

Exercise: Two photos

Find two photos of animals. Create a Web page with two buttons and the two photos. One button shows and hides one of the images. The other button shows and hides the other.

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

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

Summary

In this lesson, you learned how to show and hide an image in response to an event. You saw your first example of the if statement.

What now?

With just what you know now, you can make a slide show page. Let’s do it.


How to...

Lessons

User login

Log in problems? Try here


Dogs