Reputation: 13
I am creating a button operated set of traffic lights, i have this HTML and JAVASCRIPT
var lightStates = {
red: 0,
amber: 1,
green: 2
};
var currentState = lightStates.red;
document.getElementById('changeBtn').onclick = function() {
changeState();
};
function changeState() {
clear();
switch (currentState) {
case lightStates.red:
{
document.getElementById("red").className = "light red";
currentState = lightStates.amber;
}
break;
case lightStates.amber:
{
document.getElementById("amber").className = "light amber";
currentState = lightStates.green;
}
break;
case lightStates.green:
{
document.getElementById("green").className = "light green";
currentState = lightStates.red;
}
break;
}
}
function clear() {
document.getElementById("red").className = "light off";
document.getElementById("amber").className = "light off";
document.getElementById("green").className = "light off";
}
<html>
<head>
<script type="text/javascript" src=javasript.js></script>
</head>
<link rel="stylesheet" href="style.css">
<div class="traffic-light">
<div class="light off" id="red"></div>
<div class="light off" id="amber"></div>
<div class="light off" id="green"></div>
</div>
<button id="changeBtn">Change</button>
<input type="button" id="changeBtn" onclick="changestate" </input>
</html>
and the lights on a css sheet, the problem I am having is that when i run the code in a browser, the button does not do anything at all, what am i getting wrong?
Upvotes: 1
Views: 66
Reputation: 218798
id
values.Remove the duplicate button and the inline onclick
and include the JavaScript after the element(s):
<input type="button" id="changeBtn"></input>
<script type="text/javascript" src="javasript.js"></script>
Upvotes: 1
Reputation: 237
remove this part of your html code
<button id="changeBtn">Change</button>
<input type="button" id="changeBtn" onclick="changestate"</input>
Change it to this.
<button id="changeBtn" onclick="changestate()">Change</button>
I believe your issues are coming from not having a closing >
on your input, not having () on your onclick call & having two elements with the same id.
Upvotes: 1