Ask coding questions

← Back to all posts
Buttons not Working but no errors in javscript
MikeJMS8910 (234)

So I have a script that when the buttons are pressed their background color will change but it doesn't seem to be working and there aren't any errors either.

`<button id="blueButton" onclick="changeBlue()" style="background-color: lightblue; position: absolute; top: 55%; left: 15%;">Blue</button>
<button id="redButton" onclick="changeRed()" style="position: absolute; top: 55%; left: 35%;">Red</button>
<button id="greenButton" onclick="changeGreen()" style="position: absolute; top: 55%; left: 55%;">Green</button>

      var selected = "Blue";
      function changeBlue() {
        var colorBlue = document.getElementById("blueButton").style.backgroundColor;
        if(selected != "Red") {
          colorBlue = "lightblue";
          selected = "Blue"

      function changeRed() {
        var colorRed = document.getElementById("redButton").style.backgroundColor;
        if(selected != "Red") {
          colorRed = "red";
          selected = "Red"

      function changeGreen() {
        var colorGreen = document.getElementById("greenButton").style.backgroundColor;
        if(selected != "Green") {
          colorGreen= "green";
          selected = "green"
Answered by Coder100 (18925) [earned 5 cycles]
View Answer
Coder100 (18925)

when you do colorBlue = "lightblue", it sets your variable to the value, not the instance. Do this instead:

var colorGreen = document.getElementById("greenButton").style;
if(selected != "Green") {
          colorGreen.backgroundColor = "green";
          selected = "Green"

anything but objects will have that property aforementioned.

Remember to do this for all of them!

Baconman321 (1104)

Can you check if the if statements are firing? (Put a console.log in each of them logging their color to check if each button is in fact triggering the response.

This is useful for future problems where you can narrow the problem down to the one thing that's causing it (or multiple things).