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:

<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")

<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')">
<img id="a" src="images/pitAuto.jpg" width="802" height="602" alt="">

All input statements in a form should have the same name. The id of the main image should correspond to this name. The name/id should be different for each form. In this example the name/id is a.

In the preLoad function each image is assigned a unique label. The first character of the label corresponds to the name/id used in the form. 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.

Labels such as a2 serve a dual purpose. The first character of the label (a) indicates the id of the img statement in the body of the document. And if we concatonate the entire label (a2) with ".src" we have the variable that contains a path to the image (a2.src). In other words the label establishes a relation between the img statement and a path to the image.

Allocating images and using the first character as an id simplifies code in the body. Pre-allocating them in the preLoad function also has the advantage that images are fetched before the body executes. As a consequence they will display quickly when referenced. 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