Reputation: 1
I have two images, and I'm trying to change the image displayed every time the img element is clicked using the if and else statements. But the image only changes the first time, and clicking it the second time won't change the image back.
<div class="mode-change">
<img id="modeImg" class="" src="media/light.png" alt="Mode">
</div>
Please note that I don't know jQuery.
I tried using the if and else statement to change the picture every time the element is clicked, but the code won't run past the if statement.
let modeImg = document.getElementById("modeImg");
modeImg.addEventListener("click", changePic);
function changePic() {
if (modeImg.src === "media/light.png") {
modeImg.src = "media/dark.png";
console.log(modeImg.src);
} else {
modeImg.src = "media/light.png";
console.log(modeImg.src)
}
}
After trying out the answer provided by @Emmanuel Villalobos, and added the right operator, but I noticed that the console only returned the value of the else statement, even when the src is "media/light.png". So I tried to return the output of the image src before the if statement like so,
function changePic() {
console.log(modeImg.src);
if (modeImg.src === "media/light.png") {
modeImg.src = "media/dark.png";
console.log(modeImg.src);
} else {
modeImg.src = "media/light.png";
console.log(modeImg.src)
}
}
The console returned the absolute link as in http://localhost/study/media/light.png
instead of the media/light.png
I put in my HTML code.
Upvotes: 0
Views: 51
Reputation: 49
The problem in your conditional is that you used a single equal sign instead of two or three to compare.
This function should work as you expect:
function changePic() {
if (modeImg.src.contains("media/light.png")) {
modeImg.src = "media/dark.png";
console.log(modeImg.src);
} else {
modeImg.src = "media/light.png";
console.log(modeImg.src)
}
}
Upvotes: 1