eMe: Making a slideshow

See more about:

Where are we?

You learned how to show and hide an image. You saw the if statement in action. Now let’s make a simple slide show for your eMe.

What about? Pick something from your interesting stuff list.

This page’s goals

By the end of this page, you should:

  • Know how to control a sequence of events.
  • Know how to restart an event sequence when it gets to the end.

Slide show behavior

Let’s make sure we know what we want from the slide show.

Please try the page. Click on the arrow a few times. Notice that there are four photos. The show cycles back to the first one when it’s done.

The page is showing one image, cycling it as the user clicks.

Image cycle

Figure 1. Image cycle

We’ll actually use only one <img> tag. By changing its src attribute, we’ll change which photo the <img> tag is showing.

Suppose we gave each photo a number. This is what would be happening.

Numbered image cycle

Figure 2. Numbered image cycle

The slide number starts at 1. On each click, it goes up by one. When it gets to 4, a click sends it back to one. Each event is a step in the cycle. Click – 1 – click – 2 – click – 3 – click – 4 – click – 1 – click – 2 – ...

Let’s move closer to the actual code. Suppose we name the image files slide1.jpg, slide2.jpg, slide3.jpg, and slide4.jpg. The name of the image for the current slide would be:

slide + the slide number + .jpg

If we could put that into the src attribute of the <img> tag, it would show the current slide.

Closer to code

Figure 3. Closer to code

Here’s some pseudocode for the click() event:

Increase the slide number by one.
The new slide name is (slide + slide number + .jpg).
Set the <img> tag's src to the slide name.

Wait a minute. I forgot something. There is no slide 5. Hmm. How about this?

Increase the slide number by one.
If the slide number is more than 4, make it 1.
The new slide name is (slide + slide number + .jpg).
Set the <img> tag's src to the slide name.

That’s better.

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>Slide Show</title>
    <style type="text/css">
      #forward {
        cursor: pointer;
      }
    </style>
    <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() {
        var slide_number = 1;
        $("#slide").attr("src", "slide" + slide_number + ".jpg");
        $("#forward").click(function() {
          slide_number ++;
          if ( slide_number > 4 ) {
            slide_number = 1;
          }
          $("#slide").attr("src", "slide" + slide_number + ".jpg");
        });
      });
    </script>
  </head>
  <body>
    <h1>Slide Show</h1>
    <p><img id="slide" alt="Slide show image"></p>
    <p><img id="forward" src="forward_arrow.gif" alt="Forward"></p>
  </body>
</html>

Figure 4. The code!

Let’s look at the HTML first. Line 28 is the <img> that shows a photo. Notice that the <img> tag has id and alt attributes. The id will let us mess with the image in JavaScript. The alt is needed for the page to validate.

But there’s no src attribute in line 28. That’s because the src in set in JavaScript. Its value changes with each click.

Line 29 is the thing that users’ click on. I found the image in a clip art library I bought. The <img> tag in line 29 also has an id, because I want to attach an event to it.

The CSS for this image is in lines 7 to 9. #forward means “Find the thing with an id of forward.” The style sets the mouse cursor to the pointer, which by default looks like a hand.

Now for the JavaScript. Line 14 creates the variable slide_number, and sets its initial value to 1. This variable will go up by one every time the user clicks on the arrow.

Line 15 is:

$("#slide").attr("src", "slide" + slide_number + ".jpg");

$("#slide") says “Find everything with an id of slide.” There is only one thing with that id. Again, don’t forget the #.

"slide" + slide_number + ".jpg" computes the name of the file to show in the <img>. If slide_number is 1, then this works out to slide1.jpg. If slide_number is 4, then this works out to slide4.jpg.

The attr() function sets an attribute of a tag. There are lots of different attributes, so you need to tell attr() which one to set. Then you give it the value.

In English, this:

$("#slide").attr("src", "slide" + slide_number + ".jpg");

says:

Find the thing with an id of slide. Set its src attribute to the value "slide" + slide_number + ".jpg".

Line 16 binds code to the click() event of the forward arrow. So the code from lines 17 to 21 is run whenever the user clicks on the arrow.

Line 17 adds one to the variable slide_number. That’s what ++ does – add one to a variable. You could also write:

slide_number = slide_number + 1;

That says “Take the value of the variable slide_number, add 1 to it, and put the result into the variable slide_number.” It’s common for variables to overwrite their own values like this.

What happens when the user gets to the last slide (slide 4), and clicks on the forward image? There are no more slides! So, back to slide 1. Here’s the if statement:

if ( slide_number > 4 ) {
  slide_number = 1;
}

When slide_number > 4 is true, run the code in the braces. This sets slide_number back to 1.

Finally, line 21 changes the src attribute of the <img> tag, to show the right slide. It’s the same code as line 15.

W00f!

Tracking program execution

I’ll change the JS to this:

$(document).ready(function() {
var slide_number = 1;
$("#slide").attr("src", "slide" + slide_number + ".jpg");
$("#forward").click(function() {
  slide_number ++;
  alert("slide_number before if: " + slide_number);
  if ( slide_number > 4 ) {
    slide_number = 1;
  }
  alert("slide_number after if: " + slide_number);
  $("#slide").attr("src", "slide" + slide_number + ".jpg");
  alert("Slide file name: " + "slide" + slide_number + ".jpg")
});

Figure 5. alert()

Please try it. Notice how The alert() statements show how the program is working.

This is especially handy if there’s a bug in the program. It helps you understand what the program is doing. You can compare what you see to what you expect to see. For example, if you expect slide_number to change from 5 to 1, and it doesn’t, that’s a clue that there might be something wrong with the if.

Exercise: A slideshow

Create your own slide show of at least eight images.

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

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

Enhance the slide show

Let’s make some improvements.

Show the slide number

First, let’s show the slide number. Try my solution.

I added this to the HTML, creating a place to show the slide number:

<p>Slide number <span id="slide_number"></span>.</p>

Recall that <span> creates a spot on the page you can refer to with its id.

The I added this to the JavaScript:

$("#slide_number").text(slide_number);

I added it twice, after lines 15 and 21 of Figure 4.

Add a back button

Next I added a button to go backward in the slide show. 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>Slide Show</title>
    <style type="text/css">
      #forward, #backward {
        cursor: pointer;
      }
    </style>
    <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() {
        var slide_number = 1;
        $("#slide").attr("src", "slide" + slide_number + ".jpg");
        $("#slide_number").text(slide_number);
        $("#forward").click(function() {
          slide_number ++;
          if ( slide_number > 4 ) {
            slide_number = 1;
          }
          $("#slide").attr("src", "slide" + slide_number + ".jpg");
          $("#slide_number").text(slide_number);
        });
        $("#backward").click(function() {
          slide_number --;
          if ( slide_number < 1 ) {
            slide_number = 4;
          }
          $("#slide").attr("src", "slide" + slide_number + ".jpg");
          $("#slide_number").text(slide_number);
        });
      });
    </script>
  </head>
  <body>
    <h1>Slide Show</h1>
    <p><img id="slide" alt="Slide show image"></p>
    <p>Slide number <span id="slide_number"></span>.</p>
    <p>
      <img id="backward" src="backward_arrow.gif" alt="Backward">
      <img id="forward" src="forward_arrow.gif" alt="Forward">
    </p>
  </body>
</html>

Figure 6. Going backward

Look at line 7. This tells the browser to apply the same CSS rule to two different things. Don’t forget the ,.

Line 26 shows the — operator. It subtracts 1 from a variable.

Lines 27 and 28 make sure that slide_number does not go below 1.

Exercise: Improve your slideshow

Improve the slide show you made. Add:

  • Slide number.
  • Back button.
  • Home button. It always takes you back to the first slide.

Add JavaScript alert() statements so that you can see how the program works.

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

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

Adding image descriptions

Let’s add a description to each image, so that the user knows what s/he is looking at. Please try the page.

There are many ways to show the descriptions. I’ll use one of the easiest ways.

I’ll change the HTML so that it looks like this:

<body>
  <h1>Slide Show</h1>
  <p><img id="slide" alt="Slide show image"></p>
  <p>Slide number <span id="slide_number"></span>.</p>
  <p id="description_1" class="description">Renata as a puppy, chewing on a human's feet.</p>
  <p id="description_2" class="description">Renata wondering what is going on.</p>
  <p id="description_3" class="description">Renata loves to chase balls.</p>
  <p id="description_4" class="description">What's that? Can I eat it?</p>
  <p>
    <img id="backward" src="backward_arrow.gif" alt="Backward">
    <img id="forward" src="forward_arrow.gif" alt="Forward">
  </p>
</body>

Figure 7. HTML for image descriptions

There’s an important difference in the way I’ve implemented the slides and the descriptions. There is one tag for all the slides. It’s the <img> tag on line 44. To show a slide, we change the contents of that one tag.

The way descriptions are handled in Figure 7 is different. There are four tags for the descriptions, a separate one for each description. They’re on lines 46 to 49. To show a description, we change which tag is showing.

So if we want to show the description of slide 1, we show the element with the id of description_1 (line 46), and hide the other descriptions. To show the description of slide 2, we show the element with the id of description_2 (line 47), and hide the other descriptions.

Renata
Renata

Wait a minute. The code is wrong.

Kieran
Kieran

Where’s that?

Renata
Renata

Look at line 46. It has an id and a class. Can you do that?

Kieran
Kieran

Sure. That’s part of how the code works. We’ll talk about that in a bit.

Let’s look again at what happens when a user clicks on the “Next slide” button. Just the logic of it, not the code, not just yet.

Increase the slide number by one.
If the slide number is more than 4, make it 1.
The new slide name is (slide + slide number + .jpg).
Set the <img> tag's src to the slide name.
Hide all of the descriptions.
Show the element (description_ + slide number).

As before, the first two lines work out which slide number the user wants to see. The next two lines show that slide. The last two lines show the description. The last line uses the slide number.

So the slide number is used for two things:

  • Select the photo to show, and
  • Select the description to show.

Here’s the new JavaScript.

<script type="text/javascript">
  $(document).ready(function() {
    var slide_number = 1;
    $("#slide").attr("src", "slide" + slide_number + ".jpg");
    $("#slide_number").text(slide_number);
    $(".description").hide();
    $("#description_" + slide_number).show();
    $("#forward").click(function() {
      slide_number ++;
      if ( slide_number > 4 ) {
        slide_number = 1;
      }
      $("#slide").attr("src", "slide" + slide_number + ".jpg");
      $("#slide_number").text(slide_number);
      $(".description").hide();
      $("#description_" + slide_number).show();
    });
    $("#backward").click(function() {
      slide_number --;
      if ( slide_number < 1 ) {
        slide_number = 4;
      }
      $("#slide").attr("src", "slide" + slide_number + ".jpg");
      $("#slide_number").text(slide_number);
      $(".description").hide();
      $("#description_" + slide_number).show();
    });
  });
</script>

Figure 8. New JavaScript

Most of its the same as before. Let’s take a look.

When the page first loads, we want slide number 1 to be showing. That’s what lines 14 to 18 do. Line 14 creates a variable and sets it to 1. Line 15 shows that slide. Line 16 outputs the number of that slide.

Lines 17 and 18 are new. Here’s line 17:

$(".description").hide();

Remember that the . means class. So the line says.

Hide everything that has a class of description.

All four of the description elements have the class description. Here they are:

<p id="description_1" class="description">Renata as a puppy, chewing on a human's feet.</p>
bq. <p id="description_2" class="description">Renata wondering what is going on.</p>
bq. <p id="description_3" class="description">Renata loves to chase balls.</p>
bq. <p id="description_4" class="description">What's that? Can I eat it?</p>

So line 17 will hide all of the descriptions.

Once we’ve done that, we want to show just the description of the current slide. So line 18 is:

$("#description_" + slide_number).show();

Remember that # means id. So since slide_number is 1, this means:

Show the element with an id of description_1.

Renata
Renata

Oh, snap! That’s why each of the descriptions has an id and a class. The ids are all different. They have to be; you can’t reuse the same id on a page. The classes are all the same.

Kieran
Kieran

Right.

Renata
Renata

You use the class to refer to them all in one statement. Then you can hide everything at once.

Kieran
Kieran

Indeed.

Renata
Renata

And you use the id to refer to just one of them. Because you only want to show one at a time.

Kieran
Kieran

Aye! You got it!

Summary

On this page, you learned how to control a sequence using events, with a variable keeping track of where the page is in the sequence.

What now?

Now it’s time to do some more exercises. Yay!


How to...

Lessons

User login

Log in problems? Try here


Dogs