0

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.

2
  • 1
    When your var toggle=true; is inside your click event, your variable will be resetted on every click. So place the variable outside click function. Commented Oct 29, 2013 at 11:44
  • 2
    its working jsfiddle.net/B9ad3 Commented Oct 29, 2013 at 11:45

3 Answers 3

2

Simpler and more elegant:

var toggle = true;
alert(toggle ? "Toggle is on":"Toggle is off")
toggle = !toggle
Sign up to request clarification or add additional context in comments.

1 Comment

@pythonian29033 probably not, but op also asked how to make it simpler.
0

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

1 Comment

Yeap my fault silly mistake I included it in the function! Moved it out and its all working fine now!
0

Make sure the var toggle=true is outside the function containing the if(...) code. Otherwise toggle will keep getting initialized to true.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.