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.
You’re redeclaring a new local variable in the function because of the
varkeyword. Get rid of that.Also, there’s no reason to compare boolean variables to the boolean constants:
Note also that you don’t need the “nav” in the selectors; “id” values should be unique on the page anyway.
Using
varis 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.