javascript - How can I change an image with onclick() & if statement repeatedly? -
i new javascript , need issue.
i have 3 traffic light images want change each click. go green amber 1 click, amber red click, red green, etc.
i have code below, seems go green red first click.
any 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>
you have lights array possible states. need iterate between them.
there problem time takes load amber , red images 1st time, loaded when state changes. i've added little preloader solve problem.
fiddle demo - note use other images in demo
var demo = document.getelementbyid("demo"); // demo element , cache 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 1 currentlight index currentlight > 2 && (currentlight = 0); // if it's above 2 change 0 demo.src = lights[currentlight]; // assign url src }
Comments
Post a Comment