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...
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;
}
});
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;
}
});