Reputation: 699
I wrote this to switch between two states so when I click on something it will trigger this
var toggle=true;
if(toggle == true){
alert('Toggle is on');
toggle = false;
}
else{
alert('Toggle is off');
toggle = true;
}
It keeps alerting Toggle is on. Is there anyway I can actually 'toggle' between those two? Are there simpler ways? I am using this on a internet webpage.
Upvotes: 0
Views: 105
Reputation: 4735
Simpler and more elegant:
var toggle = true;
alert(toggle ? "Toggle is on":"Toggle is off")
toggle = !toggle
Upvotes: 2
Reputation: 5207
this is probably because you put var toggle=true;
inside the function and not before the function declaration, show us the entire function so we know what you're talking about
Upvotes: 0
Reputation: 40298
Make sure the var toggle=true
is outside the function containing the if(...)
code. Otherwise toggle
will keep getting initialized to true
.
Upvotes: 0