skip to Main Content

I’m trying to make collapsing sidebar of product categories. by using woocommerce product categories widget and a bit of code (without coding the sidebar showing all the categories & sub-categories one above another). I achieved to make a collapsing sidebar but when I click one main category – all the categories opened at once and all subcategories appear.

I didn’t find a way to give each sub-category group a unique class using jQuery only – all by woocommerce default has calls called "children".

(function($) {  
    $(document).ready(function() {
        $("li.cat-item-22").click(function() {
            $('ul.children').slideToggle();
        });
    
        $("li.cat-item-29").click(function() {
            $('ul.children').slideToggle();
        });
    
        $("li.cat-item-30").click(function() {
            $('ul.children').slideToggle();
        });
    
        $("li.cat-item-40").click(function() {
            $('ul.children').slideToggle();
        });
    
        $("li.cat-item-43").click(function() {
            $('ul.children').slideToggle();
        });
    
        $("li.cat-item-55").click(function() {
            $('ul.children').slideToggle();
        });
     
        $("li.cat-item-61").click(function() {
            $('ul.children').slideToggle();
        });
    });
})(jQuery);

2

Answers


  1. Chosen as BEST ANSWER

    It finally worked with the function below - that way i could give each 'children' class a unique id that solved my problem.

    (function($){
    
    $('ul.children').each(function(a,b,c,d,e,f,g){
    $(this).attr('id',$(this).attr('class')+a)
    })
    console.log($('body').html());
    

  2. You have to use attribute selector to get your object

    $("li[class^='cat-item-'],li[class*='cat-item-']")
    

    https://api.jquery.com/attribute-starts-with-selector/

    And then use $(this) to refer to you current object with click event

    $(document).ready(function() {
    
      $("li[class^='cat-item-'],li[class*='cat-item-']").click(function() {
        $(this).find('ul.children').slideToggle();
      });
    
    });
    .children { display:none }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul>
      <li class="cat-item-22">
        Test in li.cat-item-22
        <ul class="children">
          <li>Test in ul.children</li>
        </ul>
      </li>
    </ul>
    <ul>
      <li class="cat-item-24">
        Test in li.cat-item-24
        <ul class="children">
          <li>Test in ul.children</li>
        </ul>
      </li>
    </ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search