Reputation: 5
I'll start with the code then I'll explain:
<section>
<div id="flex">
<img id="bulb1" src="images/lightoff.png" onclick="luce(this.id)" />
<img id="bulb2" src="images/lightoff.png" onclick="luce(this.id)" />
<img id="bulb3" src="images/lightoff.png" onclick="luce(this.id)" />
</div>
</section>
function luce(bulb) {
if (bulb == "bulb1") {
var bulbsw = document.getElementById('bulb1');
if(bulbsw.src == "images/lighton.png") {
bulbsw.src = "images/lightoff.png";
} else {
bulbsw.src = "images/lighton.png";
}
}
}
The javascript code is in an external file, then no worries I have pasted it in this way to let you read it. I have three images, they represent three bulbs off. When I click on bulb1 all good, it goes on. Now I expect that if I click on bulb1 again it goes off, but nothing happens, why? Sorry I'm a beginner and I'm doing exercises to improve. Thank you very much!
Upvotes: 0
Views: 82
Reputation: 12891
If you run this script - either locally or from a webserver - the string which gets returned by querying the .src property of an image element doesn't consist of the path and the image only.
For example if you run it locally inside a folder called bulb on your d: drive it will return
file:///d:/bulb/images/lightoff.png
That means as soon as the luce function gets called it will jump right into the else block because if(bulbsw.src == "images/lighton.png")
evaluates to false.
The next time you click on that same bulb it will jump straight into the else block again because there is no way this will ever evaluate to true.
You can workaround by extracting just the filename + the extension and use this for the comparison.
function luce(bulb) {
if (bulb == "bulb1") {
var bulbsw = document.getElementById('bulb1');
var bulbImage = bulbsw.src.substring(bulbsw.src.lastIndexOf("/") + 1, bulbsw.src.length);
if (bulbImage == "lighton.png") {
bulbsw.src = "lightoff.png";
} else {
bulbsw.src = "lighton.png";
}
}
}
<section>
<div id="flex">
<img id="bulb1" src="images/lightoff.png" onclick="luce(this.id)" />
<img id="bulb2" src="images/lightoff.png" onclick="luce(this.id)" />
<img id="bulb3" src="images/lightoff.png" onclick="luce(this.id)" />
</div>
</section>
Upvotes: 1