Easy Peasy Accordion Using CSS & jQuery
This week, I worked on a responsive website project that included a section that looked like this on a typical laptop screen:
When thinking about making this site responsive, I wanted to stack each block so that it all fit clearly and cleanly when viewing the site on a mobile device (I made this change using a media query where the max-width was 480px). But after testing it, I wanted to remove the chunk of text under each heading since most visitors probably wouldn’t want to read ALL of the descriptions. My solution was to create an accordion, where all of the descriptions would be hidden until you clicked on the heading. Here’s what it would look like:
This solution may seem pretty complicated, but it only takes a bit of CSS and a few lines of jQuery.
Here’s how I did it:
Let’s create a smaller version with three sections.
NOTE: Don’t forget to include the jQuery script tag at the bottom of your HTML.
Now let’s style it:
And here is what we have:
The description in each set of <p> tags is not there! They’re hidden for now (CSS: line 18), but we will be able to reveal them once we include the jQuery.
This is where all the magic happens:
We first target each section by calling the element class on line 2. Here, we are saying that once we click on a .element div, we will do one of two things by using the ultra-handy if/else statement:
- If we have an open element that shows the description, it will close when we click on that specific element.
- Otherwise, we will remove the .show class (which, if you refer to CSS line 22, will make <p> visible) on ALL of the elements. Then, we will add the .show class to the element we just clicked (i.e. we will open that element to reveal the description).
What we end up with is a functional accordion!
Play around with it here: