Reputation: 1631
I have a simple accordian I have made with Jquery. It toggles open and close on the item and also closes down any other active items.
Here is the code:
$(document).ready(function($) {
$('#accordion').find('.accordion-toggle').click(function(){
$(this).toggleClass('activeState');
// Remove active state from other panels not selected
$("#accordian").not($(this)).removeClass('activeState');
//Expand or collapse this panel
$(this).next().slideToggle('fast');
//Hide the other panels
$(".accordion-content").not($(this).next()).slideUp('fast');
});
});
Right now I am just using the 'activeState' class to add a background colour of yellow (later I am looking to use icon classes). Now it toggles well when opening and closing the same item. But I want it to toggle/remove the activeState class when another accordian item is clicked on (then obviously append the activeState class to the newly opened accordian item. I am attempting to use the ".not()" jQuery function to remove the activeState class from any of the '.accordian-toggle' items that is not the active object being clicked on. I am here because I am not having any luck with it.
Here is the JSFiddle https://jsfiddle.net/0LLncd4d/26/ Can I please ask for some assistance in what I may have overlooked?
Upvotes: 0
Views: 151
Reputation: 921
replace the two lines
$(this).toggleClass('activeState');
$("#accordian").not($(this)).removeClass('activeState');
with
$('.accordion-toggle').removeClass('activeState');
if($(this).parent().find('.accordion-content').css('display')=='none'){
$(this).addClass('activeState');
}
Upvotes: 3
Reputation: 705
Try like this:
$(document).ready(function($) {
$('#accordion').find('.accordion-toggle').click(function(){
$(this).toggleClass('activeState');
// Remove active state from other panels not selected
$(".accordion-toggle").not($(this)).removeClass('activeState');
//Expand or collapse this panel
$(this).next().slideToggle('fast');
//Hide the other panels
$(".accordion-content").not($(this).next()).slideUp('fast');
});
});
Upvotes: 1