An image gallery: Captions

  1. Switch on click
  2. An image gallery
  3. Random image

We now have a fully working photo gallery. What can we do to improve it? Photos often have captions, and each of the <a> tags linking to our photos has a title attribute whose text would make a perfect caption. So far, we’ve only modified the attributes of HTML tags. But once we get ahold of a tag’s object, we can even modify the text that the tag surrounds. If there’s a paragraph on the page and we want to change the text of that paragraph, we can do so—as long as we can find that paragraph’s JavaScript object.

If the paragraph has an ID attribute, we can use getElementById to get ahold of that paragraph. In the HTML for gallery.html, find the <img> tag with the ID “frame”. Underneath it—but still inside the <div> that surrounds it—add an empty paragraph with the ID “caption”:

<div>

<img id="frame" src="…" />

<p id="caption"></p>

</div>

Add two lines to the switchImage function:

function switchImage(link) {

var imageFrame = document.getElementById("frame");

imageFrame.src = link.href;

var captionParagraph = document.getElementById("caption");

captionParagraph.innerHTML = link.title;

return false;

}

Try this, and now when you click on one of the links, not only will the image change but a caption will display beneath the image.

Captions: innerHTML

The innerHTML is the stuff between the beginning and ending of a tag. If a paragraph was <p>Hello, world!</p> and you set the innerHTML to “Goodbye, cruel world!”, the result is as if it were <p>Goodbye, cruel world!</p>.

String replace

As you might guess from the name, innerHTML can contain HTML as well as straight text. This means that the innerHTML can contain <a> tags, <em> tags, and any tag that legally fits inside the tag you’re modifying. Try replacing “captionParagraph.innerHTML = link.title” with:

var caption = link.title;

caption = caption.replace(

'William Miller',

'<a href="http://wikipedia.org/wiki/William_Miller_(engraver)">William Miller</a>'

);

captionParagraph.innerHTML = caption;

The “replace” method on a string looks for the first parameter and replaces it with the second parameter. In this case, it looks for the text “William Miller” and it replaces it with a link to Wikipedia’s William Miller entry.

image 4
  1. Switch on click
  2. An image gallery
  3. Random image