Reputation: 11
I have an image of a person wearing a hat. I have «master.png» image of the hat (by itself) over this image which will change to a different image (same hat/different color) everytime the user clicks a different color swatch below.
The javascript function works but I haven't been able to assign the color variable values to my swatches. So only the last js src image listed appears regardless of which swatch you click. I'm also not sure if my javascript variable code is correct.
I haven't been able to find anything on the web about how to do this. Please help!
Here is the code:
<script type="text/javascript">
function hat(color)
{
var color = ['redhat', 'bluehat', 'blackhat'];
document.getElementById("master").src="images/redhat.png";
document.getElementById("master").src="images/bluehat.png";
document.getElementById("master").src="images/blackhat.png";
}
</script>
<img id="hat" src="images/manwearinghat.png" width="100%" class="center">
<img id="master" src="images/masterhat.png" width="100%" alt=" " name="master">
<img src="images/swatchs/redswatch.png" width="69" height="69" onclick="hat('redhat');" value="redhat" style="z-index:3">
<img src="images/swatchs/blueswatch.png" width="69" height="69" onclick="hat('bluehat');" value="bluehat" style="z-index:3">
<img src="images/swatchs/blackhat.png" width="69" height="69
" onclick="hat('blackhat');" style="z-index:3">
Upvotes: 1
Views: 486
Reputation: 1879
This code isn't very compact, but it will work. HTML:
<img id="hat" src="images/manwearinghat.png" width="100%" class="center">
<div id="master"></div>
<div>
<img src="images/swatchs/redswatch.png" width="69" height="69" onclick="hat('redhat');"
value="redhat" style="z-index:3">
<img src="images/swatchs/blueswatch.png" width="69" height="69" onclick="hat('bluehat');"
value="bluehat" style="z-index:3">
<img src="images/swatchs/blackhat.png" width="69" height="69
" onclick="hat('blackhat');" style="z-index:3">
</div>
Javascript:
function hat(color){
if (color == 'bluehat'){
document.getElementById('picture').innerHTML=<img id="master"
src="images/bluehat.png" width="100%" alt=" " name="master">
if (color == 'blackhat'){
document.getElementById('picture').innerHTML=<img id="master"
src="images/blackhat.png" width="100%" alt=" " name="master">
if (color == 'redhat'){
document.getElementById('picture').innerHTML=<img id="master" src="images/redhat.png"
width="100%" alt=" " name="master">
};
Upvotes: 0
Reputation: 51
Since you are already passing name of the color all you need to do is
function hat(color) {
document.getElementById("master").src = "images/" +color+".png";
}
to change the image.
Upvotes: 0
Reputation: 60414
You could use something as simple as this:
function hat(color) {
document.getElementById("master").src = "images/" + color + ".png";
}
Upvotes: 2