2

I'm trying to change the background color on each click.

var button = document.querySelector("button");
var body = document.querySelector("body");
var color = true;

button.addEventListener("click", function(){
    if(color){
        body.style.backgroundColor = "purple";
        color != color;
    }
    else if (!color){
        body.style.backgroundColor = "green";
    }
});
2
  • What's wrong with your code? Commented Dec 10, 2016 at 1:46
  • correct color != color; to color = false and \ or, simplify your function to function(){ color ? body.style.backgroundColor = "purple" : body.style.backgroundColor = "green"; }; altogether. Commented Dec 10, 2016 at 3:14

1 Answer 1

3

A small modification. You need to toggle the variable on every click. You could simplify your code further by getting rid of the if else and replace it with else

var button = document.querySelector("button");
var body = document.querySelector("body");
var color = true;

button.addEventListener("click", function() {
  if (color) {
    body.style.backgroundColor = "purple";
  } else {
    body.style.backgroundColor = "green";
  }
  // or equivalent with a ternary operator:
  body.style.backgroundColor = color ? "purple" : "green";

  // color != color is a comparison, but you want an assignment:
  color = !color;
});

Check Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

I see, i knew i was using the comparison wrong, i just couldn't put my finger on it :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.