Javascript code sample

<!-- Switch images script -->
<script type="text/javascript">
  function swapImage(id,primary,secondary) {
    src=document.getElementById(id).src;
    if (src.match(primary)) {
      document.getElementById(id).src=secondary;
    } else {
      document.getElementById(id).src=primary;
    }
  }
</script>

This snippet of Javascript enables a viewer to click on an image to replace it with another one. By clicking repeatedly, the two images are toggled.

I use this on my teaching pages where students are encouraged to think about what the outcome of some mathematical operation is. By clicking on the image, they can check their prediction. The page about Fourier transforming in practice contains several examples. Another obvious application would be in a game of Memory.

How does it work?

Fig.: Waterwheel at Pontrhydygroes in colour or in black and white. Click image to toggle colour. (Alternatively, view desaturated image here.)

When clicking the image of the waterwheel at Pont-rhyd-y-groes, it is replaced by another picture - in this case, by a desaturated (black and white) version of the same scene.

The function goes in the <head> section of the page. It takes three arguments: id identifies a particular image shown on the page, primary is the image displayed at first, and secondary the one shown after clicking the image. Further mouseclicks toggle between the two.

document.getElementById().src retrieves the full URL from the src attribute in the <img> tag of the image after identifying it by its id attribute. Even if src is specified as a relative path, the function will always return the full URL. Since primary is the filename of the image as shown originally, we can search that URL for the filename. If primary is currently on display, we reset the src attribute to secondary. Otherwise, secondary will already be on display, and we change it back to primary.

<img
  id="desat"
  onclick="swapImage(
    'desat',
    'swapimage_col.jpg',
    'swapimage_bw.jpg'
  )"
  src="swapimage_col.jpg"
  title=""
  alt="Fig.: Waterwheel."
/>
<span style="font-size:0.6em">
  Click image to toggle colour.
  (Alternatively, view desaturated image
  <a href="swapimage_bw.jpg">here</a>.)
</span>

To make this work, the <img> tag needs to have an id attribute, and our swapImage() function needs to be connected to the onclick event handler in the <img> tag, as shown in the box on the right.

Obviously, the reader needs to know that the image is clickable, so it's best to include a sentence explaining what happens if you click the image. And since not everybody has Javascript switched on, there should be a link to the alternative image so that it can be displayed separately if needed.