Expandable FAQ items with no JavaScript

Recently I needed to create an FAQ page on a ReactJS based single page application. The page should have expandible/collapsible question/answer pairs.

I took to Google to see how others were doing it, but quickly realised that adding in (yet another) third party react library was not the way I wanted to do it. I generally prefer simplicity over everything else and I could easily create a nice looking solution, that works purely with html and css. No JavaScript required. This approach has been tested to work in at least Chrome (pc, Mac and Android), Safari (Mac and iPhone), Opera, Edge and IE11.

To begin with, we have simple question/answer markup like this:

The most common solutions involves adding/removing classes, that control wether the answer-part is shown or hidden. And then there is a lot of React or JQuery sprinkled on top to achieve an animated expand/collapse effect. Adding and removing classes requires JavaScript, which adds unnecessary complexity. Therefore to maintain the state of wether the answer should be shown or not, we’ll introduce a checkbox:

The checkbox is of course not supposed to be shown, it will be hidden with css later. To make it possible to check/uncheck the checkbox even though it is hidden, we’ll wrap the while thing in a label:

Finally, to get the good ol’ arrow-down/up effect, we’ll add a simple ‘>’ as well, that can be turned with css to point up or down. In the real solution, of course we’ll use a graphic or svg, but for simplicity, let’s use a simple character:

The next step is to add css to hide the answer and the checkbox, make the question look clickable and rotate the “arrow”. This involves adding some css classes to the markup:

The input could also be hidden using display: none, but then it would not be possible to use keyboard navigation to check/uncheck it. The border around the collapser is there to provide a subtle visual cue, for keyboard navigation.

Then we need css to show the answer and rotate the arrow, when the checkbox is checked:

Finally, to make it look nice, a css transition to first grow the answer, then fade it in, while the arrow rotates and vice-versa, when the answer gets hidden again:

And the final solution looks like this:

See the Pen FAQ items with zero javascript by Anders Poulsen (@andpoulsen) on CodePen.

Leave a Reply

Close Menu