In this example, two other arrays besides the built-in image array are created to first construct all needed image object constructors, then the array elements are used as the object reference to the swapped on and off state images in the showOn and showOff functions. First, look at the two new arrays. The first array's elements declare the on state image object constructors and the second declares the off state image object constructors.
var onImage = new Array()

onImage["home"] = new Image()
onImage["home"].src = "../images/homeOn.gif";

onImage["contact"] = new Image()
onImage["contact"].src = "../images/contactOn.gif";

onImage["ab"] = new Image()
onImage["ab"].src = "../images/aboutOn.gif";

var offImage = new Array()

offImage["ab"] = new Image()
offImage["ab"].src = "../images/aboutOff.gif";

offImage["home"] = new Image()
offImage["home"].src = "../images/homeOff.gif";

offImage["contact"] = new Image()
offImage["contact"].src = "../images/contactOff.gif";
And the functions:
function showOn(imgName) {
document.images[imgName].src = onImage[imgName].src

function showOff(imgName) {
document.images[imgName].src = offImage[imgName].src
The naming convention used is the same as in the previous example, and the functions are invoked in exactly the same way. The big difference is that the object reference is stored in a reference to an array element, and a string-to-object conversion is not required. What you should notice here is the versatility of arrays - their elements can hold more than just strings and numbers.

Some people find this construction confusing, and prefer the construction of the previous example. The construction you use is completely up to you, there is no major benefit with either construction.

View the Source

Home | Contact