In this case:
var button = document.querySelector("button");
var body = document.querySelector("body");
var white = true;
button.addEventListener("click", function() {
if (white) {
body.style.backgroundColor="pink";
} else {
body.style.backgroundColor="white";
}
white = !white;
});
<button>Click</button>
You change the global variable white
and after function execution it will be true
or false
, so the function will trigger the color to another (if it was white, after click it will be pink and vise versa).
But in this case:
var button = document.querySelector("button");
var body = document.querySelector("body");
button.addEventListener("click", function() {
var white = true;
if (white) {
body.style.backgroundColor="pink";
} else {
body.style.backgroundColor="white";
}
white = !white;
});
<button>Click</button>
All local function variables are removed after the function execution is finished. Your white
variable is always true
on function start, so the first if
statement works every time (changes the background to pink only).