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:


$(document).on('click', '.collapsible h2', function(evt){
$('.collapsible h2:not(.clicked)').removeClass('selected').next().slideUp(500);
} else {
$('.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 *