How to make an accordion

An accordion is a common component for showing users a lot of content and letting them dive into what they want. Great for FAQs or pages that provide details on a variety of things.

Accordions can be tricky to implement. They require css and javascript and can be edited in a wysiwyg or created with fields. You can put one in your body text and edit it in the wysiwyg, or use fields to fill in the values.

Let's try using Collapse Text module. With this, you can type your accordion content within [collapse][/collapse] tags and it will display using the Details element. There is a theme hook and template suggestion for this, so it will be very easy to style how we want.

Here's some sample content, after installing the module and configuring the editor to use the filter.

Collapse Text example in CKEditor

And here's how that looks in Bartik.

Details element in Bartik theme

 

Not bad, but how can we make it better?

Let's use the styles dropdown in the editor to apply the [collapse] tags. I've added the Styles dropdown to the editor and configured a <collapse> element with the label Accordion. You can use this <collapse> element in place of the token, the module will display it as well. You can do this in the Text formats and editors configuration. This allows you to select some text and pick a style from the dropdown to wrap the text with an element and class.

CKEditor accordion style configuration

I quickly ran into some limitations with this. First, there was no way to setup the title using styles. The content author still needs to know how [collapse] works, and with the <collapse> element, you can't see the tokens in wysiwyg because it's an html element that has no display.

 

Let's back up and try the WYSIWYG Templates module to add a button and insert the code. I've added the button to ckeditor and configured this template.

WYSIWYG Templates accordion example

CKeditor is wrapping the [collapse] tags in <p> but this is ok.

 

Now we have a button to choose from available Ckeditor templates, including our accordion. You can see what it puts in the WYSIWYG in the background.

WYSIWYG accordion example

It works!

Accordion demo

 

This solution with get the job done, although it has some quirks. There are other ways to approach this, which I'll revisit another time.