Collapsible definition lists with jQuery
Here’s a lightweight snippet for creating a collapsable defintion list. A client wanted a way to present a large page of text with some sections collapsed. The site is also built in CMS so I wanted a solution that tapped into semantic code that would easy to create and edit using a wysiwyg editor. TinyMCE in this case. I’ll set up an example page if anyone wants it. Let me know.

Simply write a simple definition list using semantic code. No classes necessary - hooray!
<dl>
<dt>Definition term here will be clickable</dt>
<dd>Definition description here will hide and show when corresponding term is clicked</dd>
</dl>
Here’s the Javascript for the jQuery. I’ve also added a class to show a different icon for expanded and collapsed definition terms.
$(document).ready(function() {
// set all <dt> elements CSS classes to contracted for icon
// and hide their corresponding <dd> element
$(’dt’).addClass(’contracted’);
$(’dd’).hide();
// set <dt> toggle function to expand/contract the following <dd> element
// and toggle the contracted CSS class to switch the icon
$(’dt’).toggle(function() {
$(this).removeClass(’contracted’);
$(this).next().fadeIn();
}, function() {
$(this).next().fadeOut(’normal’,function() {
$(this).prev().addClass(’contracted’) // class is added in the callback to chain events
});
});
});
It’s worth pointing out that each definition term <dt> will need it’s corresponding description <dd> as the clicks are targeting the next element. Try it and see what happens. Also, it’s a good idea to create some CSS rules to style the <dt> elements with an appropriate hover style. You can do this will jQuery or just CSS using a dt:hover (not strictly standards compiant but understood by most browsers).
January 11th, 2009 at 2:44 am
Hey man thanks a lot for that used it on my blog:
http://johnsbeharry.com/blog/2009/01/10/list-of-plans-for-2009/
Works like a charm. I didn’t put the hover class on it though. Did add a background of an arrow + some padding
January 15th, 2009 at 12:00 pm
Great! glad it was useful to you.
Quick note: Your arrows don’t sit inside the box when viewed on Firefox and Safari on the Mac - they are off to the left so you can’t quite tell that they are down arrows.