Skip to main content

Accordions

Demo

Installation

Import the function into the JavaScript file of your project

import { Accordions } from "@overdog/fn"

Create and initialize an instance

new Accordions(".accordions-group-wrapper", {
  // your options here - see options below
}).init()

Add the Tailwind variants to the plugins section of your config file.

If you are using multiple elements from Overdog FN that require the same variants, you only need to add them once. You can also modify the data attributes added to each function using the attributes parameter {}.

module.exports = {
   // ...
   plugins: [
      plugin(function ({ addVariant }) {
         addVariant("is-open", "&[data-fn-is-open]")
         addVariant("parent-is-open", "[data-fn-is-open] &")
      })
   ]
}

Twig template Code

{#
   EMBED BLOCKS
   {% block accordionsHeading %} - use with embed to override the title block
   {% block accordionsContent %} - use with embed to override the content block
#}


{# You probably want to change this array for a Craft CMS query #}
{% set contentArray = [
      { content: "Oh yeah!", title: "Hello, this is an accordion" },
      { content: "Hum, not really.", title: "Wait, are you sure?" }
   ] 
%}

{# 
   Example targetPrefix
   You can set a value as a prefix for targetPrefix outside your for loop
   Useful in matrix blocks 
#}
{% set targetPrefix = "demo-" %}

{% if contentArray|length %}

   <div class="accordions-group-wrapper">{# your wrapper classes - used when you create your JS instance #}
      {% for item in contentArray %}
      {# edit the target to fit your needs #}
      {% set target = targetPrefix is defined ?  targetPrefix ~ loop.index : loop.index %}
      {# content #}
      <div class="mb-4" data-fn-accordion>
         <h3>
            <button 
               class="bg-white border border-slate-300 block p-4 text-left w-full parent-is-open:bg-gray-300"
               data-fn-target="ac-{{ target }}"
               aria-expanded="false" 
               aria-controls="ac-{{ target }}"
               >
               {%- block accordionsHeading %}{# override with embed if needed #}
                  {% if item.title %}{{ item.title }}{% endif %}
               {% endblock -%}
            </button>
         </h3>
         <div id="ac-{{ target }}" class="h-0 overflow-hidden transition-height duration-300">{# do not style this div #}
            <div class="py-4">
               {%- block accordionsContent %}{# override with embed if needed #}
                  {% if item.content %}
                     <div>{{ item.content }}</div>
                  {% endif %}
               {% endblock -%}
            </div>
         </div>
      </div>
   {% endfor %}
   </div>
{% endif %}

Options