Ben Line

Shopify Accordion

10/14/2019 • ☕️ 1 min read

Liquid

{% if section.settings.title != blank %}
<div class="accordion-title">
  <h1>{{ section.settings.title }}</h1>
</div>
{% endif %}

<div class="accordion-container">
  {% for block in section.blocks %}
  <button class="accordion">{{ block.settings.heading }}</button>
  <div class="panel">
    <div class="panel-inner">
      {{ block.settings.content }}
    </div>
  </div>
  {% endfor %}
</div>

JSON

{% schema %}
{
  "name": "Accordion",
  "class": "index-section",
  "max_blocks": 20,
  "settings": [
    {
      "type": "text",
      "id": "title",
      "label": "Section Title",
      "default": "Section Title"
    }
  ],
  "blocks": [
        {
        "type": "text",
        "name": "Block Item",
        "settings": [
        {
          "type": "text",
          "id": "heading",
          "label": "Heading",
          "default": "Heading here"
        },
        {
          "type": "textarea",
          "id": "content",
          "label": "Content",
          "default": "Text here"
        }
      ]
    }
  ],
  "presets": [
    {
      "name": "Accordion",
      "category": "Additional",
      "blocks": [
        {
          "type": "text"
        }
      ]
    }
  ]
}
{% endschema %}

CSS

.accordion {
	background: #ffffff;
    color: #000000;
    cursor: pointer;
    padding: 18px 0;
    font-family: "Metropolis", sans-serif;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    -webkit-transition: 0.4s;
    -o-transition: 0.4s;
    transition: 0.4s;
}

.active, .accordion:hover {
}

.accordion:after {
    content: '\2228';
    color: #000000;
    font-weight: bold;
    float: right;
    margin-left: 5px;
	margin-right: 15px;
}

.active:after {
    content: "\2227";
}

.panel {
    border-bottom: 1px solid #000;
    color: #58595B;
    max-height: 0;
    overflow: hidden;
    -webkit-transition: max-height 0.2s ease-out;
    -o-transition: max-height 0.2s ease-out;
    transition: max-height 0.2s ease-out;
}
.panel-inner {
	padding: 0 0 1em 0;
}

Javascript

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    } 
  });
}