0

I have a simple jQuery script to show/hide list elements accordion-style along with a global boolean array to save which lists are shown/hidden. However, when switching from show/hiding different sublists, the boolean array goes undefined, ie (I call function with form_nav_links to show that list, then when I try to show help_nav_links right after, the array is undefined and requires an extra click). Can someone help me fix this? Here is what I have:

var listsOn = Boolean[2];
listsOn = [false, false];
var form_links = 0, help_links = 1;

function toggleView(subList) {
    var i;

    switch(subList){
        case "form_nav_links":
            i = form_links;
            break;
        case "help_nav_links":
            i = help_links;
            break;
        };

    if(listsOn[i]){
        $("." + subList).slideUp(1000);
        listsOn[i] = false;
        }
    else {
        $("." + subList).slideDown(1000);
        listsOn[i] = true;
        }

Thanks in advance!

4
  • 4
    Boolean[2]; in javascript means nothing useful. Commented Jun 27, 2012 at 18:17
  • How is that called ? Can you set a fiddle ? Commented Jun 27, 2012 at 18:19
  • use slideToggle() and never use globals :) Commented Jun 27, 2012 at 18:21
  • ^^ well that's just sooo much better, varela. That beautifully knocks it down to 1 line =) Commented Jun 27, 2012 at 19:30

2 Answers 2

1

You really ought to be using an associative array here:

var listsOn = {
  form_nav_links: false,
  help_nav_links: false
};

function toggleView(subList) {
  if(typeof listsOn[subList] !== 'undefined') {
    if(listsOn[subList]{
        $("." + subList).slideUp(1000);
        listsOn[subList] = false;
    }
    else {
        $("." + subList).slideDown(1000);
        listsOn[subList] = true;
    }
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

wow, strict equal to 'undefined' string, what else you expect from typeof?
ah, I had that originally but then got stuck trying to access the bools like listsOn.blah (I'm less than a week into JS)
@varela: no reason not to use strict equal and it's easier to have an established habit of using strict equality than switching and leaving it to the maintainer to determine whether an unstrict equality operator is acceptable.
0

I solved the issue by using slideToggle() instead

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.