Reputation: 3017
var orangeMode = true
flip = function() {
orangeMode = !orangeMode;
}
document.getElementById("box").addEventListener("click", flip);
if (orangeMode) {
document.getElementById("circle").style.backgroundColor = "orange";
} else {
document.getElementById("circle").style.backgroundColor = "blue";
}
Manually changing the variable from true to false on the first line flips the color of the circle from orange to blue, but tapping the box in the corner is meant to flip between them, but doesn't work. Feel like there is something basic I'm doing wrong here?
Upvotes: 0
Views: 118
Reputation: 34168
You could actually check the color and get rid of the global variable:
var flip = function() {
var baseColor = "orange";
var currcolor = document.getElementById("circle").style.backgroundColor;
document.getElementById("circle").style.backgroundColor = (currcolor == baseColor) ? "blue" : baseColor;
}
document.getElementById("box").addEventListener("click", flip);
Upvotes: 0
Reputation: 87203
Although, moving the code to change colour inside the event handler will work, I'd suggest to use classList
API.
Create a CSS class to set the background color to blue and toggle this class when the box is clicked.
classList.toggle('className')
will add the class if it is not already added on the element otherwise it'll remove the class.
document.getElementById("box").addEventListener("click", function() {
document.getElementById('circle').classList.toggle('blue');
});
#box {
width: 50px;
height: 50px;
position: absolute;
bottom: 0;
right: 0;
background-color: red;
}
#circle {
width: 50px;
height: 50px;
background: orange;
border-radius: 50px;
position: absolute;
top: 50%;
left: 50%;
}
#circle.blue {
background: blue;
}
<div id="box"></div>
<div id="circle"></div>
Upvotes: 0
Reputation: 68393
check the orange value in flip method itself
var orangeMode = true
flip = function() {
orangeMode = !orangeMode;
if (orangeMode) {
document.getElementById("circle").style.backgroundColor = "orange";
} else {
document.getElementById("circle").style.backgroundColor = "blue";
}
}
document.getElementById("box").addEventListener("click", flip);
Upvotes: 2