Dan
Dan

Reputation: 13

HTML button not working with my javascript

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

Answers (2)

David
David

Reputation: 218798

  1. You're trying to invoke the function in two separate ways, both inline and as an event handler.
  2. The markup is invalid, both with typos and with multiple identical id values.
  3. The event handler is being assigned before the element actually exists.

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

Captain Squirrel
Captain Squirrel

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

Related Questions