Reputation: 2802
I have the below code, being used to create an accordion effect by toggling an .active
class. Upon click of .section-header
, I am toggling a class on both the header and the .section-content
. This is working well.
However, as mentioned, this is to create an accordion effect, which is amde up of multiple .accordion-section
<div>
tags. I need to adjust the jquery in order to remove all .active
classes from every .accordion-section
other than the one that is currently active. At the moment, the clicking of .section-header
toggles an .active
class on ALL .section-content
<div>
tags.
Thanks.
HTML
<div class="accordion-section">
<a class="section-header">
<h3>Title</h3>
</a>
<div class="section-content">
<div>Content</div>
</div>
</div>
JS
$('.accordion-section .section-header').click(function(){
$(this).toggleClass('active');
$(this).siblings().toggleClass('active');
});
Upvotes: 0
Views: 1646
Reputation: 685
$('.accordion-section .section-header').click(function(){
// Check to see the initial state of the element
var isActive = $(this).hasClass('active');
// first remove the active class from all other section headers within this accordion section
$('.accordion-section')
.find('.section-header, .section-content')
.removeClass('active');
// Get the header and content for this section
var sectionHeaderAndContent = $(this)
.closest('.accordion-section')
.find('.section-header, .section-content');
// Toggle Active State: Set final active state based on state when clicked
(isActive) ? sectionHeaderAndContent.removeClass('active'): sectionHeaderAndContent.addClass('active');
});
Upvotes: 1