I have an accordion which closes one element when another is clicked, as well as simply clicking once to open and twice to close (accordionButton).
All is working well apart from the adding and removing of two classes, which control if it has an open or close arrow ‘accordionButtonActive’ & ‘accordionButtonNotactive’ As this is being controlled on click it’s not removing and adding the new class if it’s closed by clicking another one rather than clicking again to close which works perfectly.
I’m new to Jquery and was chuffed I managed to get this working as far as I have, now I’m a little baffled to making this last part function as it should.
JQuery:
$("div.accordionButton").addClass("accordionButtonNotactive");
//ACCORDION BUTTON ACTION
$('div.accordionButton').click(function() {
if($(this).next().is(':visible')) {
$('div.accordionContent').slideUp('normal');
$(this).addClass("accordionButtonNotactive").removeClass("accordionButtonActive");
} else {
$('div.accordionContent').slideUp('normal');
$(this).next().slideDown('normal');
$(this).removeClass("accordionButtonNotactive").addClass("accordionButtonActive");
}
});
//OPEN FIRST
$("#open").trigger('click');
});
Simple HTML:
<div class="accordionButton" id="open">Title</div>
<div class="accordionContent">
<p>Content</p>
</div>
You could just remove the active-class and add the inactive-class for any sibling, when any header is clicked:
Example
Additionally, you might find it easier to add one style for
.accordionButtonand overwrite that for.accordionButton.active, so that you only have to deal with one class.You could also use
toggleClass, in order to only have to deal with that one class once, for your current element, rather than usingaddClassin one condition, andremoveClassin another.Example