Search code examples
jqueryhtml-listsaccordionsubmenu

Jquery: only show the UL with a child LI set to class = active


I have this kind of structure for a menu:

<ul id="accordion">
 <li><a href="#">Books</a>
  <ul>
    <li><a href="thrillers.html">Thrillers</a></li>
    <li><a href="scifi.html">Sci-fi</a></li>
    <li><a href="nf.html">Non-fiction</a></li>
  </ul>
 </li>
 <li><a href="#">Games</a>
  <ul>
    <li><a href="rpg.html">RPG</a></li>
    <li><a href="sim.html">Simulations</a></li>
    <li><a href="action.html">Action</a></li>
  </ul>
 </li>
</ul>

(etc.)

Now, we people click on "RPG" i want the Games submenu to be open on the RPG-page. So, I decided to add a class to the LI that is selected:

...
<ul>
  <li class="active"><a href="rpg.html">RPG</a></li>
  <li><a href="sim.html">Simulations</a></li>
  <li><a href="action.html">Action</a></li>
</ul>
...

Now, the thing I am trying to do is to have jQuery find the UL with a class="active" and then open that UL.

I just this jQuery:

<script>

$(document).ready(function () {

    //hide all submenu's onLoad
    $('#accordion li').children('ul').slideUp('fast');  

    $('#accordion a.item').click(function () {

        /* FIRST SECTION */

        //slideup or hide all the Submenu
        $('#accordion li').children('ul').slideUp('fast');  

        //remove all the "Over" class, so that the arrow reset to default
        $('#accordion a.item').each(function () {
            if ($(this).attr('rel')!='') {
                $(this).removeClass($(this).attr('rel') + 'Over');  
            }
        });

        /* SECOND SECTION */        

        //show the selected submenu
        $(this).siblings('ul').slideDown('fast');

        //add "Over" class, so that the arrow pointing down
        $(this).addClass($(this).attr('rel') + 'Over');         

        return false;

    });

});

</script>

What do I need after the onLoad part to only have the one I want to be opened?


Solution

  • This may help:

    $('#accordion > li > ul > li.active').parent().slideDown('fast');