A very simple jQuery accordion

This is a very simple script that hides and reveals the next element in the DOM when a level 2 heading is clicked. The script begins by hiding all paragraphs within the #accordion div.

Button 1

Brownie applicake donut oat cake. Faworki cotton candy jelly gummies biscuit chupa chups. Ice cream jujubes tart ice cream sugar plum wafer.

Button 2

Tiramisu candy canes muffin tiramisu marshmallow muffin I love halvah toffee. Jujubes chocolate chocolate bar wafer topping. Croissant fruitcake croissant. Candy canes I love I love I love gummies oat cake.

Button 3

Chocolate bar macaroon chocolate bar tiramisu. Dessert I love candy canes cake powder halvah apple pie applicake. I love pie I love brownie I love.

Button 4

Liquorice croissant oat cake sesame snaps gingerbread oat cake macaroon gummies bear claw. Macaroon jelly-o croissant I love jujubes halvah. Pie cake jelly beans wafer. Chupa chups muffin sweet roll cake pudding.

The accordion is a very popular design pattern and with jQuery, it's really easy to implement.

<!-- load jQuery from Google CDN -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/
jquery.min.js"></script> <script> $ready(function(){ $("#accordion p").hide() $("#accordion h2").click(function() { $(this).next().slideToggle(); }); }); </script>

Here is a fragment of the HTML:

<div id="accordion">
	<h2>Button 1</h2>
	<p>Brownie applicake donut…

This script functions perfectly. The only slight problem is that if you view the DOM in FireBug, you will notice that jQuery uses an inline style to hide the paragraphs, which is OK but not ideal. A better way might be to create a CSS rule to hide the paragraphs and then toggle that rule, avoiding the use of inline styles.

Note: In this example, the script is shown as it would appear if placed in the HTML file and is done only for convenience in demonstrating how it works. The best practice solution would be to place the script in an external file and call it like this:

<script src="filename.js"></script>

jQuery selectors work in exactly the same way as CSS selectors, so the script will work just as well from an external .js file as it will from the .html file.