It just about that time some good old fashioned web programming. Today we’re learning how to create an accordion style page – using my most favorite of tools: jQuery and CSS. We will try to accomplish an accordion that is so simple, yet useful enough for you to use in your existing pages. Ready to get started – let’s begin.
Look at the sample mark up below:
We will use the H5 tags as our “Clicker” – once clicked, will hide the contents right underneath it. Click it again, and it will show the contents again.
We start by calling the jQuery library, followed by the document.ready() call:
We then loop through each of our particular heading tag (in this case, all of H5). Once it finds all of them, it checks to see if right next to it is another H5 tag; if it’s not, it adds a class of “clicker” to it and appends a span with a minus (-) sign in it:
If you investigate your code so far – you will see that only the H5 tags that have content OTHER than H5 tags have the class “clicker” and the span tag with a minus (-) sign in it:
Now let’s code the click events:
Now that we have our designated clickers, we create a couple of functions that toggle at every click.
The first action, hides the contents below “$(this)” – which is the tag you just clicked. Remember – we only want to hide the contents up until the next H5 tag. It also changes the content of the span into a plus (+) symbol.
The second action shows the contents below, and changes the span to a minus (-) symbol.
At this point you already have a functional accordion. If you’re applying the code to an existing page, you are already working with the current styles. Although, using CSS3 for say the plus (+) and minus (-) span looks pretty cool – which I’m sure you’d want to use.
Add this code to your styles:
Of course you have to replace the #wrap h5 with your own class / ids. This creates the css3 button you see in the demo. This code is courtesy of Zurb’s Super Awesome buttons with CSS3 and RGBA:
And that is it! You have yourself an accordion page powered by jQuery. Feel free to grab this code and improve it. Maybe refactor it into a more plugin like code – make it more reusable. Or even – fix the choppiness issue in the slideUp / slideDown animation in certain browsers. In any case, please leave a comment on what you think of this code.
You might also be interested in these articles regarding jQuery accordions:
- Simple Accordion w/ CSS and jQuery
- Exactly How to Create a Custom jQuery Accordion
- Grid Accordion with jQuery