Javascript: swap images of different sizes

I found a clever solution to a common problem today. If you use javascript to swap one image for another, usually the two images are the same size. However, what if you need to load an image of a different size? It will lose proportions, because javascript can’t detect the dimensions of an image it hasn’t loaded yet. I found today a neat solution: preload the image without displaying it. Then javascript will be able to take its dimensions.

modelshot = new Image()
modelshot.src = "/images/600/EBH9022_MOD.jpg"
hatshot = new Image()
hatshot.src = "/images/600/EBH9022.jpg"

function swapImage(img_name){
if (document[img_name].src.search(/_MOD/) == -1) {
document[img_name].src = '/images/600/' + [img_name] + '_MOD.jpg';
document[img_name].width = modelshot.width;
document[img_name].height = modelshot.height;
} else {
document[img_name].src = '/images/600/' + [img_name] + '.jpg';
document[img_name].width = hatshot.width;
document[img_name].height = hatshot.height;
}
}

example

One comment

  1. Stephen Rahn says:

    Thanks, Richard. I hope all is well in Portland!