Reputation: 23
Html code :
<img src="images/assets/plus.png" alt="Earth" id="pic" class="portrait" onclick="changeImage()" />
Javascript:
var newsrc = "minus.png";
function changeImage() {
if (newsrc == "minus.png") {
document.images["pic"].src = "images/assets/minus.png";
document.images["pic"].alt = "minus";
newsrc = "minus.png";
} else {
document.images["pic"].src = "images/assets/plus.png";
document.images["pic"].alt = "plus";
newsrc = "plus.png";
}
}
I am using these code to change image onclick.Now i want that when i click the minus image again it will come back to plus image again .How can i do that?
Upvotes: 1
Views: 75
Reputation: 180
You should use document.getElementById("pic")
instead of what you have because the document.images[]
method returns an array. In your case it returns "[object HTMLImageElement]".
You should also move var newsrc = "minus.png"
inside your function. I'm not sure the function will recognize the variable the way you have it.
Finally you should not set the newsrc
variable inside your if.
That being said this code is much more simplistic:
function changeImage() {
var pic = document.getElementById("pic");
var x = document.getElementById("pic").src;
if (x == "images/assets/plus.png"){
pic.src = "images/assets/minus.png"
// Plus whatever else you want to do
} else {pic.src = "images/assets/plus.png"
// Plus whatever else you want to do
}
}
Upvotes: 1
Reputation: 18995
if minus.png
then set to minus.png
? Else won't be never performed. Should be if not minus, then minus, otherwise plus. Change ==
to !=
. And if you want image with id "pic", you should use getElementById()
.
Edit:
for multiple images use following and change id="pic"
to class="pic"
in <img>
:
function changeImage() {
if (newsrc != "minus.png") {
for(var i = 0; i<document.getElementsByClassName("pic").length; i++) {
document.getElementsByClassName("pic")[i].src = "images/assets/minus.png";
document.getElementsByClassName("pic")[i].alt = "minus";
}
newsrc = "minus.png";
} else {
for(var i = 0; i<document.getElementsByClassName("pic").length; i++) {
document.getElementsByClassName("pic")[i].src = "images/assets/plus.png";
document.getElementsByClassName("pic")[i].alt = "plus";
}
newsrc = "plus.png";
}
Upvotes: 1