An image gallery: Switch on click

  1. Block that click
  2. An image gallery
  3. Captions

If you look in the HTML, you’ll see that the <img> tag has an ID of “frame”. When we call the switchImage function, we want to find the element with that ID in the document.

Replace switchImage with:

function switchImage(link) {

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

imageFrame.src = link.href;

return false;


Now, when you click on a link the image in the display should switch immediately to that link’s image.

Find any element by ID

The document object has a method called getElementById. XHTML tags can have a unique identifier as one of their attributes. No “id” attribute can be used more than once in an XHTML page, so getElementById is always specific to a single element.

Look carefully at the method’s name: the Id portion of the name is capital-I and lowercase-d. JavaScript functions are case sensitive, so using getElementByID, as I often do, will fail.

Setting the src attribute

Most attributes of HTML tags can be modified using JavaScript, and that includes the src attribute of <img> tags. The switchImage function sets the “src” attribute of the <img> tag to the “href” attribute of the <a> tag the visitor clicks on.

  1. Block that click
  2. An image gallery
  3. Captions