HTML Radio Buttons Change Images

This document explains a clever way to change images with HTML radio buttons and JavaScript. These examples were taken from my Infrared tutorial. This code works under the latest versions of Firefox, Chrome, Internet Explorer, and Safari.

1: JPEG - Auto WB
2: JPEG - custom WB
3: JPEG - after processing
4: Raw - after processing
5: Raw - 100% crop of sky
6: JPEG - 100% crop of sky

Let's do it again but swap two images this time.

1: JPEG: Auto WB
2: JPEG: New WB
3: Raw: New WB
4: Raw: New WB + Custom Profile

The following snippets are from this page:

<head>
<script type="text/javascript">
function preLoad() {
  a1 = new Image;
  a1.src = 'images/pitAuto.jpg';  
  a2 = new Image;
  a2.src = 'images/pitJpgWb.jpg';
  a3 = new Image;
  a3.src = 'images/pitJpgWbFinal.jpg';
}
function im(image) {
  document.getElementById(image[0]).src = eval(image + ".src")
}
</script>
</head>    

<body onLoad="preLoad()">
<form autocomplete="off">
  <input type="radio" name="a" onClick="im('a1');" checked>
  <input type="radio" name="a" onClick="im('a2');">
  <input type="radio" name="a" onClick="im('a3');">
</form>
<img id="a" src="images/pitAuto.jpg" width="802" height="602" alt="">
</body>

A two character label is associated with each image in the preLoad function. The first character corresponds to the id of the main image. The second character indicates the new image replacing it. In this example the main image has an id of a and the new images replacing it are a1, a2, and a3.

The input statements in the body invoke function im passing the appropriate label. In function im we concatenate .src to the label and evaluate it to obtain the image path. Using the first character of the label (image[0]) this path is assigned to the main image.

Since the preLoad function references the images before the body executes they will display quickly when the radio button is pressed. Setting autocomplete="off" in the form causes it to properly reset if the page is refreshed. I suggest you use your browser to view the source of this page.

Tom Niemann
Portland, Oregon
epaperpress.com