Search code examples
jquerymenuaccordionselected

How to slide up or down ul elements based on selected item


I have the following menu for an application I am building and I'm having a hard time applying some jquery rules to hide the subcategories of the menu.

What I want to do is as follows:

When I first load the page, I want the children( child1, child2 etc) of each category to slide up (close). Through code, I keep track of the selected item so if I load a different page, the menu should be build according to the following rule:

If I apply a class "selected" to, say, Category1, then I want its children to slide down. If the class "selected" is applied to a child, then I want its parent ul to be expanded also.

Case 1: selected class applied to Category1

<ul>     
<li class="selected has-children first-child">Category1</a>                       
 <ul>
  <li class="first-child">Child1</li>
  <li class=" ">Child2</li>
  <li class=" ">Child3</li>
  <li class=" ">Child4</li>
  <li class=" ">Child5></li>
  <li class=" ">Child6</li>
  <li class="last-child">Child6</li>
 </ul>
</li>
<li class="has-children">Category2</a>
 <ul>
  <li class="first-child">Child1</li>
 </ul>
</li>
<li class="has-children last-child">Category3</a>
 <ul>
  <li class="first-child">Child1</li>
  <li class="last-child">Child2</li>
 </ul>
</li>
</ul>

Case 2: selected class applied to child4 (ul should be expanded)

<ul>     
<li class="selected has-children first-child">Category1</a>                       
 <ul>
  <li class="first-child">Child1</li>
  <li class=" ">Child2</li>
  <li class=" ">Child3</li>
  <li class="selected ">Child4</li>
  <li class=" ">Child5></li>
  <li class=" ">Child6</li>
  <li class="last-child">Child6</li>
 </ul>
</li>
<li class="has-children">Category2</a>
 <ul>
  <li class="first-child">Child1</li>
 </ul>
</li>
<li class="has-children last-child">Category3</a>
 <ul>
  <li class="first-child">Child1</li>
  <li class="last-child">Child2</li>
 </ul>
</li>
</ul>

Τhank you in advance


Solution

  • Do you want any interactivity with expanding/collapsing these menus? Or do you just want to apply this functionality once on pageload? If it's the second, then you need to define class names:

    li.parent {
       display:none;
    }
    
    li.selected {
       display:block;
    }
    

    You need to apply this class name to all parent elements. Any parent elements which have the class name selected will automatically show their child elements. Then, using this jQuery:

    $(function() {
    
       $('li.parent li').each(function() {
          var parent = $(this).parent('ul').parent('li');
          if($(this).hasClass('selected') || parent.hasClass('selected')) {
             parent.show();
          }
       });
    
    });
    

    This loops through every li child element and checks whether it has the class name selected. If it does, it shows the parent li.