Javascript Image Switcher

Click on a color swatch to change the flower's color. Note* Not too much time was spent on making the image look realistic. Just an example of how an image can be changed dynamically without reloading the page which is sometimes useful for shops selling more than one color of a particular item.

 

 

 

 

The HTML

All you really need is a clickable image or in this case a div container, that will act as your button and a target image that will be changed as a result. Of course you can lay this out any way you like. Here is what is used for this example. The first argument in the swap function corresponds to the image that will be defined the the script. The second argument indicated the target, in this case imgColor.

<div class="left-container">
	<div class="color-box" id="blue" onclick="swap(1, 'imgColor')"></div>
	<div class="color-box" id="red" onclick="swap(2, 'imgColor')"></div>
	<div class="color-box" id="purple" onclick="swap(3, 'imgColor')"></div>
	<div class="color-box" id="yellow" onclick="swap(4, 'imgColor')"></div>
</div>

<div class="right-container">
	<img alt="" name="imgColor" src="images/flower-yellow.jpg" />
</div>

The CSS

And the styling used for this example

.left-container{float:left;}
.right-container{float:right;}
.color-box{border: 1px solid ; width: 50px; height: 50px; margin-bottom:20px;}
#blue{background-color: rgb(51, 51, 255);}
#red{background-color: rgb(255, 51, 51);}
#purple{background-color: rgb(204, 51, 255);}
#yellow{background-color: rgb(255, 204, 51);}

The Javascript

The script initializes the images that will be used in an array so there will be no lag for the image loading when the user clicks the button. The swap function simply replaces the source image with the requested one.

Simply include the script in the head of your document or in an external script.

var aryImages = new Array();

aryImages[1] = "images/flower-blue.jpg";
aryImages[2] = "images/flower-red.jpg";
aryImages[3] = "images/flower-purple.jpg";
aryImages[4] = "images/flower-yellow.jpg";

for (i=0; i < aryImages.length; i++) {
	var preload = new Image();
	preload.src = aryImages[i];
}

function swap(imgIndex, imgTarget) {
	document[imgTarget].src = aryImages[imgIndex];
}

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Lines and paragraphs break automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options

Verify Your Humanity
This question is for testing whether you are a human visitor and to prevent automated spam submissions.