I’ve tried to switch by boolean but for some reason it won’t work.
function onBall3Click() {
var ball3 = document.querySelector('.ball3')
var isOn = true;
if ( isOn )
{
ball3.style.backgroundColor = 'Yellow'
ball3.innerText = 'ON'
}
else
{
ball3.style.backgroundColor = 'Grey'
ball3.innerText = 'OFF'
}
isOn = !isOn
ball3.style.width = ball3Size + 'px';
ball3.style.height = ball3Size + 'px';
}
I put a boolean with if
and else
and expected the colors and text to change.
3
Answers
Try changing the
if/else
statement as follows:There is no possible scenario in which this condition would ever be
false
:The variable is explicitly defined as
true
and then immediately tested to see if it’strue
. Which it will be.It sounds like you want the scope of the variable to be outside the function. For example:
This way the variable is only defined once, and the same instance of the variable is used each time the function is invoked. Which will allow the current value of the variable to persist after the function completes and be read again the next time the function is called.
You should use data attributes to handle state-keeping.
Here is an example of a global click listener that checks if the element that you clicked is a ball. If it is a ball, toggle the state of the data attribute using the
dataset
property.The CSS will now control the look of the ball.