Reputation: 37
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";
}
});
Upvotes: 2
Views: 1165
Reputation: 55740
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;
});
Upvotes: 3