Why is my function to change the background color run (alert works), but does not change the color?

Currently learning Javascript, complete newbie. Trying to write a function that, when a button is clicked, toggles the background color of the <body> element from white to purple and vice-versa.

The alert is working so the function is being run, but the color never changes.

Have absolutely no idea what's going on...

Thanks in advance.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
  <title>My Title</title>

</head>
<body>>
  <button>Click me!</button>

  <h1>I am an h1!</h1>
    <p id="first" class="special">Hello</p>
    <p class="special">Goodbye</p>
    <p>Hi Again</p>
  <p id="last">Goodbye Again</p>


  <!-- SCRIPS -->
  <script type="text/javascript" src="exercises.js"></script>
</body>
</html>

JavaScript:

var color_button = document.querySelector("button");
var is_purple = false;

color_button.addEventListener("click", function() {
    alert("clicked");
    if (is_purple = false) {
        document.querySelector("body").style.backgroundColor = "purple";
        is_purple = true;
    }
    else {
        document.querySelector("body").style.backgroundColor = "white";
        is_purple = false;
    }
});

1 answer

  • answered 2018-10-11 19:14 ControlAltDel

    Your problem is that you are using the single equals in your comparator. Single equals is for assigning a value to a variable, not for comparison.

    color_button.addEventListener("click", function() {
        alert("clicked");
    //what you had
    //    if (is_purple = false) {
    //what it should be
          if (is_purple === false) {
            document.querySelector("body").style.backgroundColor = "purple";
            is_purple = true;
        }
        else {
            document.querySelector("body").style.backgroundColor = "white";
            is_purple = false;
        }
    });