0

I've seen several posts on here about how to update a Javascript global variable. I'm trying to use it as a toggle, so that when the function runs again it does the opposite of what it just did (or, that is, whatever I've set it to do. )

It's not working, and I'm frusturated because I'm getting no errors from the developer console, either.

var display_menu_toggle = false;
function display_menu() {
        if (display_menu_toggle == true) {
        document.getElementById('barometer').style.display = "none";
        document.getElementById('finance').style.display = "none";
        return false;
    }
    document.getElementById('barometer').style.display = "block";
    document.getElementById('finance').style.display = "block";
    display_menu_toggle = true;
    return true;
}
5
  • 3
    You are never setting display_menu_toggle back to false. Commented Jan 17, 2015 at 7:54
  • 1
    Instead of display_menu_toggle = true; you need to toggle it display_menu_toggle = !display_menu_toggle; Commented Jan 17, 2015 at 7:54
  • What about it is not working? It looks like it should toggle the first time (false to true), but not necessarily to false again. Commented Jan 17, 2015 at 7:54
  • @felixKling Thanks! It works. Now, if you want the points you're gonna have to submit it in terms of an answer. Commented Jan 17, 2015 at 7:59
  • first of all you don't need to use if (display_menu_toggle == true) you could simply write if (display_menu_toggle). Secondly you should assign a false value to display_menu_toggle when you are done with it. Commented Jan 17, 2015 at 8:55

1 Answer 1

1

As others have said, you aren't changing the value of display_menu_toggle for both conditions. Consider:

var display_menu_toggle = false;

function display_menu() {
    document.getElementById('barometer').style.display = display_menu_toggle? "none" : '';
    document.getElementById('finance').style.display = display_menu_toggle? "none" : '';
    display_menu_toggle = !display_menu_toggle;
}

It's usually best to toggle style.display between none and '' (empty string) so that when not hidden, the element returns to its default or inherited style, whatever that might be.

Sign up to request clarification or add additional context in comments.

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.