Reputation: 13
I am new to javascript and need some help with an issue.
I have 3 traffic light images that I want to change with each click. Go from green to amber with one click, then amber to red with another click, then from red to green, etc.
I have some code below, but it seems to go from green to red with the first click.
Any help is appreciated.
Thanks.
<!DOCTYPE html>
<html>
<body>
<button onclick="nextLight()">Click here</button>
<img id="demo" src="green.png">
<script>
function nextLight() {
var lights = ["blank.png", "green.png", "amber.png", "red.png"]
if (document.getElementById("demo").src == lights[1]) {
document.getElementById("demo").src = lights[2];
} else if (document.getElementById("demo").src == lights[2]) {
document.getElementById("demo").src = lights[3];
}
}
</script>
</body>
</html>
Upvotes: 1
Views: 1636
Reputation: 191976
You have the lights array as the possible states. All you need is to iterate between them.
There is a problem with the time it takes to load the amber and red images for the 1st time, as they are loaded only when the state changes. I've added a little preloader to solve that problem.
fiddle demo - note that I use other images in the demo
var demo = document.getElementById("demo"); // get the demo element and cache it
var lights = ["green.png", "amber.png", "red.png"]; // array of lights srcs
var currentLight = 0; // current light index holder
lights.forEach(function(src) { // image preloader
new Image().src = src;
});
function nextLight() {
currentLight++; // add one to currentLight index
currentLight > 2 && (currentLight = 0); // if it's above 2 change it back to 0
demo.src = lights[currentLight]; // assign the url to the src
}
Upvotes: 1
Reputation: 761
To do this, i think this way is much easier :
var lights = ['', '', '', ''];
var currentLight = 0;
// This version will loop (Go from red to blank at the end)
function nextLight() {
currentLight = (currentLight + 1) % lights.length;
document.getElementById("demo").src = lights[currentLight];
}
// This version do what you want (no loop, just display each image and then do nothing)
function nextLight() {
// Test if the next is not out of range
if(currentLight + 1 < lights.length - 1) {
document.getElementById("demo").src = lights[++currentLight];
}
}
Upvotes: 1
Reputation: 25634
I would suggest using a switch
statement:
function nextLight() {
var demo = document.getElementById("demo");
var lights = [
"", // blank
"http://i.imgur.com/oisXdU3.png", // green light
"http://i.imgur.com/qmwYgq7.png", // orange light
"http://i.imgur.com/fs6Rl1W.png" // red light
];
switch(demo.src){
case lights[1] : demo.src = lights[2]; break;
case lights[2] : demo.src = lights[3]; break;
case lights[3] : demo.src = lights[1]; break;
}
}
<button onclick="nextLight()">Click here</button>
<img id="demo" src="http://i.imgur.com/oisXdU3.png" height="100">
Upvotes: 0