How to Create a Simple Accordion Script


Today I created a simple accordion script to collapse a lengthy bit of inline text on a page. The challenge was trying to collapse not only simple items, but also sub-items on the page. While the process of creating the accordion script was relatively straightforward (as seen below), the majority of time went into redesigning the paragraphed text to be wrapped in unordered list items!

I had to also place within this code the ability to reconfigure the height of the newly expanded page (as there was a footer underneath). All it took was the ability to get the $("ul#accordion").outerHeight() and reapply this new height to its parent container and then have jQuery modify the height of the parent container.

For the sake of brevity I’ve only included the core elements needed to see the simple multi-level accordion in action.

To see this as a working example check it out on jsfiddle.

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<style>
ul#accordion, ul#accordion ul { margin: 0; }
ul#accordion li, ul#accordion ul li { list-style: none; margin: 0; }
.heading { border-bottom: 2px solid #DDD; margin: 10px 0 3px 0; display: inline-block; width: 100%; font-weight: 400; color: #000; padding-left: 20px; }
.sub-heading { border-bottom: 2px solid #DDD; margin: 10px 0 5px 0; display: inline-block; width: 100%; font-weight: 400; font-style: italic; color: #000; padding-left: 20px; }
.item-content { display: none; }
.items { display: none; }
</style>
<script>
$(document).ready(function() {
$("a.heading").click( function() {
$(this).next().toggle();
$(this).css('outline', 'none');
return false;
});
$("a.subhead").click( function() {
$(this).next().toggle();
$(this).css('outline', 'none');
return false;
});
});
</script>
</head>
<body>
<!– the basic html structure of the page was something like this –>
<ul id="accordion">
<li>
<a href="#expand1" class="heading">Heading 1</a>
<ul id="expand1" class="items">
<li>
<a href="#subarea1A" class="subhead">Sub-Head 1A</a>
<ul id="subarea1A" class="item-content">
<li>
<p>Hello World!</p>
</li>
</ul>
</li>
<li>
<a href="#subarea1B" class="subhead">Sub-Head 1B</a>
<ul id="subarea1B" class="item-content">
<li>
<p>Hello Universe!</p>
</li>
</ul>
</li>
</ul>
</li>
<li>
<a href="#heading2" class="heading">Heading 2</a>
<ul id="heading2" class="items">
<li>
<a href="#subarea2" class="subhead">Sub-Head 2</a>
<ul id="subarea2" class="item-content">
<li>
<p>Goodbye!</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</body></html>
view raw accordion.html hosted with ❤ by GitHub

Recent Posts