Custom Accordion Snippet using jQuery

Whenever I’ve built my own accordion script in jQuery, it’s always had the same problem: when you click on the collapsible that’s already open, it closes itself, then immediately reopens. Looking for alternative accordion scripts, I’ve noticed everyone else’s seems to have the same problem, so I came up with a deliciously simple way to solve it.

First, a little background. The reason this is happening is completely logical and due to the synchronous nature of jQuery animation. The way most developers go about their accordions is to make sure all others are closed, then open the requested accordion. This method works great unless you want to be able to close an accordion. Without further ado, here’s the easy solution:

HTML:
<div>
<h2>First</h2>
<p>Content</p>
</div>
<div>
<h2>Second</h2>
<p>Content</p>
</div>

Javascript:
$(document).on('click', '.collapsible h2', function(evt){
$(this).addClass('clicked');
$('.collapsible h2:not(.clicked)').removeClass('selected').next().slideUp(500);
if($(this).hasClass('selected')){
$(this).removeClass('selected').next().slideUp(500);
} else {
$(this).addClass('selected').next().slideDown(500);
}
$('.collapsible h2').removeClass('clicked');
});

Easy, right? Embarrassingly so. But I didn’t see any good examples online, so here you are.

Update 4/10: Fixed a bug in the :not selection.

Leave a Reply

Your email address will not be published. Required fields are marked *