Expand collapsable list to active element

Viewed 101

I created an expandable list in HTML using js and CSS:

The HTML code is pretty big so I pasted it in a fiddle here: https://jsfiddle.net/escozul/x2r13weo/17

the js code is here:

    function prepareList() {
      $('.product-categories').find('li:has(ul)').click( function(event) {
          if (this == event.target) {
            $(this).toggleClass('expanded');
            $(this).children('ul').toggle('medium');
          }
          return false;
        })
        .addClass('collapsed').children('ul').hide();
    
            //Create the toggle 
            var toggle = false;
        $('#listToggle').unbind('click').click(function(ev){
            if(toggle == false){
              $('li.collapsed').addClass('expanded');
              $('li li.collapsed').parent().show('medium');
              $('#listToggle').text("Collapse All");
              toggle = true;
            }else{
              $('li.collapsed').removeClass('expanded');
              $('li li.collapsed').parent().hide('medium');
              $('#listToggle').text("Expand All");
              toggle = false;          
            }
          });
    
      $('.product-categories').find('li').click( function(event) {
        siteUrl =  $(this).attr('value');
          
                  return false;
        });
    }
    
    prepareList();

The expandable list works just fine. And the collapse all does too. I also have it set up to default to a collapsed-all state.

However, I can't figure out how to have it default to a collapsed all EXCEPT the list items that have the class current-cat and their parents that use class current-cat-parent

here is an example from the HTML:

<li class="cat-item cat-item-44 cat-parent current-cat-parent"><a href="https://www.paramythi.com.gr/product-category/girls-clothing/">GIRLS</a> <span class="count">498</span>
      <ul class="children">
        <li class="cat-item cat-item-64 cat-parent current-cat-parent"><a href="https://www.paramythi.com.gr/product-category/girls-clothing/baby-girls-clothing/">ΒΡΕΦΙΚΟ</a> <span class="count">134</span>
          <ul class="children">
            <li class="cat-item cat-item-341"><a href="https://www.paramythi.com.gr/product-category/girls-clothing/baby-girls-clothing/%ce%b1%ce%bc%ce%ac%ce%bd%ce%b9%ce%ba%ce%bf/">Αμάνικο</a> <span class="count">1</span></li>
            <li class="cat-item cat-item-335"><a href="https://www.paramythi.com.gr/product-category/girls-clothing/baby-girls-clothing/%ce%b3%ce%bf%cf%85%ce%bd%ce%ac%ce%ba%ce%b9/">Γουνάκι</a> <span class="count">3</span></li>
          </ul>
        </li>
      </ul>
</li>

Do you have some ideas to make this list load collapsed by default except if some ements carry the classes current-cat and current-cat-parent?

0 Answers
Related