0

I'm having trouble with setting variables for some opening and closing menus. I need to have a variable I can query as I have other click functions going on that will open and close different menus, so I can't use a toggle.

I don't understand why the following code does not work. Please could someone advise as I can't quite get it, I understand variable scope, but I think the way the jQuery does the click function is confusing me. Or perhaps there is a better pattern to follow for this kind of functionality..

var opentags = false;

$('a#tags').click(function () {

    if (opentags == true) {
            $('nav#tags').slideUp(); 
            // and other stuff
            var opentags = false;
    } else {
            $('nav#tags').slideDown();
            // and other other stuff 
            var opentags = true;
    }});

Thanks in advance.

2 Answers 2

2

You're redeclaring a new local variable in the function because of the var keyword. Get rid of that.

Also, there's no reason to compare boolean variables to the boolean constants:

  if (opentags) {
    $('#tags').slideUp();
    opentags = false;
  }
  else {
    $('#tags').slideDown();
    opentags = true;
  }

Note also that you don't need the "nav" in the selectors; "id" values should be unique on the page anyway.

Using var is a really important thing in general, of course, so don't get the idea that it's a bad thing. It's just that in this case you want to access the variable declared outside the function scope.

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

1 Comment

I never used to use var to declare but recently started, now I fully understand. Thanks.
0

var opentags creates a new local variable, which only lives inside that callback.
You want to set the existing global variable.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.