This is a tutorial for beginners with some basic knowledge of HTML and CSS. If you’re more advanced, you might want to look at this one, too.
In this example, let’s say we have a list of questions and answers that we want to show as an accordion. An accordion usually works like this: only the questions are seen, and when you click on one, the answer expands below it. When you click on a different question, the previously shown answer hides and the new answer expands.
Write the markup
For a list of questions and answers, you can use the oft-overlooked definition list element. Any similar markup pattern will work; this one is handy since it’s not often used for other things.
<dl class="accordion">
<dt>Why is the sky blue?</dt>
<dd>Because lorem ipsum</dd><dt>Why is grass green?</dt>
<dd>Because lorem ipsum</dd>
</dl>
Use whatever questions you want in thes and whatever content you want for the answers in the corresponding. Repeat the <dt> and <dd> sets as many times as needed.Include jQuery and a script fileBefore the closing body tag of your html file, include a script link to the latest version of jQuery and to a blank script.js file that you create. It’s good to get in the practice of keeping your scripts separate, maybe even in their own directory.
In your script file
Create a blank function and call it from inside the jQuery ready method. Nothing will happen yet!var accordion = function() {
};jQuery(function($) {
accordion();
});
The following lines go in your empty accordion function:// first, hide all the answers:
$('.accordion dd').hide();$('.accordion dt').click(function(){
// after clicking a question, close any open answers in the list:
$(this).siblings('dd').slideUp();// show the answer (item directly after the question) if it is currently hidden
if($(this).next().is(':hidden')) {
$(this).next().slideDown();
}
});
And that’s it! Now it will work as described above. Here’s the full example without code comments.Extra creditYou should probably make the questions look clickable so people will know to click them. The bare minimum would be to add this to your CSS, which will change the cursor when hovering the question so it looks like a link:.accordion dt {
cursor: pointer;
}You could also wrap the questions in a link, but this will require some other changes to your markup and jQuery.You might also notice that the questions are visible for a second or so when first opening the page. That’s because we are hiding the questions with jQuery which is called after the page loads. Viewers without javascript will see the fully expanded question list. Avoid this flash of unstyled content by adding display:none; to a .accordion dd CSS rule, and you can get rid of the first line in the accordion function.Have fun :)