Accordian filter expanding and contracting all when clicked Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Accordian filter expanding and contracting all when clicked without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a product page that contains a sidebar of filters for the product. Each product contains a set of tags that are used to create the filters for that page. I am trying to put the filter groups into accordions which I have managed to do. However, when I click to expand or contract one of the group they all expand or contract.

I believe it is because I am setting each of the accordions to active when clicked. However I am struggling to set only the group I click to active.

The HTML Code below is looped for each filter group that the product have.

HTML Code:

  <h5><a href="#" class="tgl_btn">{{ cat_item }}</a></h5>
  <div class="tgl_c">
    <ul class="advanced-filters">   
      {% comment %}
      Loop through collection tags
      {% endcomment %}
      {% for tag in collection.all_tags %}
      {% assign cat = tag | split: '_' | first %}              
      {% if cat != tag and cat_item == cat %}
      {% comment %}
      Strip out tag category prefix and add/remove link for tag filtering
      {% endcomment %}
      {% if current_tags contains tag %}
      <li class="advanced-filter active-filter" data-group="{{ cat_item }}" data-handle="{{ tag | handle }}">{{ tag | remove_first: cat_item | remove_first: '_' | link_to_remove_tag: tag }}</li>
      {% else %}
      <li class="advanced-filter" data-group="{{ cat_item }}" data-handle="{{ tag | handle }}">{{ tag | remove_first: cat_item | remove_first: '_' | link_to_add_tag: tag }}</li>
      {% endif %}
      {% endif %}
      {% endfor %}
    </ul>
  </div>

JS Code

  $(".sidebar h5").click(function (e) {
    e.preventDefault();

    $(this).parent().find(".tgl_c").slideToggle(300);
    if ($(this).hasClass("active")) {
      $(this).removeClass('active');
    } else {
      $(this).addClass('active');
    }
  });

Screenshot:

enter image description here

Answer

$(this).parent().find(".tgl_c").slideToggle(300);

… gets the parent then finds all .tgl_c and calls the slideToggle() method. Instead, try:

$(this).next().slideToggle(300);
We are here to answer your question about Accordian filter expanding and contracting all when clicked - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji