Show hide categories

Show hide categories

I have the following jquery code
  1. <script type="text/javascript">
    <!--//--><![CDATA[//><!--
        $(document).ready(function() {
            $("#root ul").each(function() {$(this).css("display", "none");});
            $("#root .category").click(function() {
                var childid = "#" + $(this).attr("childid");
                if ($(childid).css("display") == "none") {$(childid).css("display", "block");}
                else {$(childid).css("display", "none");}
                if ($(this).hasClass("cat_close")) {$(this).removeClass("cat_close").addClass("cat_open");}
                else{$(this).removeClass("cat_open").addClass("cat_close");}
            });
        });
    //--><!]]>
    </script>












How can I make it so when someone selects a subcategory under a different main category the previous main category and subcategories are closed? Below is my php code for building the navigation menu.

  1. $queryrootc = mysql_query("SELECT * FROM categories ORDER BY order_by ASC");
    echo "<ul id=\"root\" class=\"menu\">";
    $r=100;
    $g = 1;
    while($querymc = mysql_fetch_array($queryrootc)){
        if ($querymc['parentid'] == 0){
            echo "<li><a href=\"javascript:void(0);\" childid=\"c_".$r."\" class=\"cat_close category\">&nbsp;</a>
                      <a href=\"javascript:void(0);\">".$querymc['category']."</a>";
            //Get all results that have the parent id of the root
            $querychksubs = mysql_query("SELECT * FROM categories WHERE parentid = '".$querymc['categoryid']."' ORDER BY order_by ASC");
            $querycntchksubc = mysql_num_rows($querychksubs);
            if ($querycntchksubc){
                echo "<ul id=\"c_".$r."\">";
                while($querychksubsresults = mysql_fetch_array($querychksubs)){
                    $querysubs2 = mysql_query("SELECT * FROM categories WHERE parentid = '".$querychksubsresults['categoryid']."' ORDER BY order_by ASC");
                    $querycntsubs = mysql_num_rows($querysubs2);
                    if ($querycntsubs){
                        echo "<li><a href=\"javascript:void(0);\" childid=\"c_".$g."\" class=\"cat_close category\">&nbsp;</a>
                                <a href=\"javascript:void(0);\">".$querychksubsresults['category']."</a><ul id=\"c_".$g."\">";
                        while($getsubs = mysql_fetch_array($querysubs2)){
                            echo "<li>".$getsubs['category']."</li>";
                        }
                        echo "</ul></li>";
                    } else {
                        echo "<li>".$querychksubsresults['category']."</li>";
                    }
                $g++;
                }
                echo "</ul></li>";
            } else {
                echo "</li>";
            }
        }
    $r++;
    }
    echo "</ul>";


































ANY HELP MUCH APPRECIATED....