[Solved] why doesnt the colour of my boxes change when prompted and confirmed?


This worked for me.

Explanation:

  1. I noticed that JavaScript cannot read element.style from the .white class, but could do so when I inserted in-line CSS to each element. This is demostrated in the following jsfiddle.

  2. You were using the this scope in your function, without actually providing what this actually is. So, I passed a this argument in the click event handler, and since this cannot be used as a function parameter, changed it to e.

function myFunction(e) {
  if (confirm("Press a button!") == true) {

    if (e.style.backgroundColor == "white")
      e.style.backgroundColor = "yellow";
    else if (e.style.backgroundColor == "yellow")
      e.style.backgroundColor = "red";
    else if (e.style.backgroundColor == "red")
      e.style.backgroundColor = "white"
    else
      e.style.backgroundColor = "white";
  } else {
    txt = "You pressed Cancel!";
  }

  if (confirm('Are you sure you want to save this thing into the database?') == true) {
    // Save it!
  } else {
    // Do nothing!
  }
}

var blocks = document.getElementsByClassName("foo");
for (i = 0; i < blocks.length; i++) {
  blocks[i].addEventListener("click", function() {
    myFunction(this);
  });
}
.foo {
  float: left;
  width: 30px;
  height: 30px;
  margin: 5px;
  border: 1px solid rgba(0, 0, 0, .2);
  border-radius: 25%;
}

.whole {
  float: left;
  width: 900px;
  height: 900px;
  margin: 5px;
  border: 1px solid rgba(0, 0, 0, .2);
}
<div class="whole">
  <div id="centerbox1" class="foo" style="background:white;">A1</div>
  <div id="centerbox2" class="foo" style="background:white;">A2</div>
  <div id="centerbox3" class="foo" style="background:white;">A3</div><br><br>

  <div id="centerbox4" class="foo" style="background:white;">B1</div>
  <div id="centerbox5" class="foo" style="background:white;">B2</div>
  <div id="centerbox6" class="foo" style="background:white;">B3</div>
</div>

2

solved why doesnt the colour of my boxes change when prompted and confirmed?