Reputation: 1359
I'm trying to use the function onclick when pressing on an img. I would like to change a big and main img ("mainPants") according to the small img that was pressed. There is a problem with my code - every 'click' on the small img changes the main img to the last one (red pants).
here is my code:
<img id="mainPants" src="images/bluePants.png">
<img class="img1" id="pBlack" onclick="changeImage()" src="images/blackPants.png">
<img class="img1" id="pPink" onclick="changeImage()" src="images/pinkPants.png">
<img class="img1" id="pRed" onclick="changeImage()" src="images/redPants.png">
<script>
function changeImage(){
var blackPants = document.getElementById("pBlack");
var pinkPants = document.getElementById("pPink");
var redPants = document.getElementById("pRed");
var newImg = document.getElementById('mainPants');
blackPants.addEventListener('onclick', function(){
newImg.src = "images/blackPantsBig.png";
}());
pinkPants.addEventListener('onclick', function(){
newImg.src = "images/pinkPantsBig.png";
}());
redPants.addEventListener('onclick', function(){
newImg.src = "images/redPantsBig.png";
}());
};
</script>
Upvotes: 0
Views: 1360
Reputation: 633
You run all your callbacks on every click:
blackPants.addEventListener('onclick', function(){
newImg.src = "images/blackPantsBig.png";
}()); // these "()" brackets run function right after it is created
You also bind all callbacks twice - the first time in HTML with onclick="changeImage()"
attribute and the second time with an addEventListener
. Try that:
<script>
function changeImage(e) {
var newImg = document.getElementById('mainPants');
switch (e.target.id) {
case 'pBlack':
newImg.src = "images/blackPantsBig.png";
break;
case 'pPink':
newImg.src = "images/pinkPantsBig.png";
break;
case 'pRed':
default:
newImg.src = "images/pinkPantsBig.png";
}
}
</script>
Upvotes: 1
Reputation: 1359
<img class="img1" id="pBlack" onclick="changeImage(this)" src="images/blackPants.png">
<img class="img1" id="pPink" onclick="changeImage(this)" src="images/pinkPants.png">
<img class="img1" id="pRed" onclick="changeImage(this)" src="images/redPants.png">
<script>
function changeImage(img) {
var newImg = document.getElementById('mainPants');
switch (img.id) {
case 'pBlack':
newImg.src = "images/blackPantsBig.png";
break;
case 'pPink':
newImg.src = "images/pinkPantsBig.png";
break;
case 'pRed':
default:
newImg.src = "images/redPantsBig.png";
}
}
</script>
Upvotes: 0