Reputation: 737
I have an accordion on a site I am working on. It has an annoying bug which I can't figure out.
If you click on the arrow, the accordion will open and close correctly. If you click on the title, the accordion will open but will simply bounce when you try to close it.
Both the title and the arrow are within the same anchor so I understand why this is happening.
The code is:
<div class="accordion">
<div class="accordion-section">
<div class="tab">
<a class="accordion-title accordion-section-button l2" href="#accordion-205">
<h3>How do you differ from estate agents?</h3>
</a>
<div id="accordion-205" class="accordion-section-content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc mattis ante eget quam volutpat, ac pulvinar massa ornare.</p>
</div>
</div>
<div class="tab">
<a class="accordion-title accordion-section-button l2" href="#accordion-204">
<h3>Why would an estate agent prefer speaking or dealing with yourself?</h3>
</a>
<div id="accordion-204" class="accordion-section-content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc mattis ante eget quam volutpat, ac pulvinar massa ornare.</p>
</div>
</div>
</div>
</div>
$(document).ready(function() {
function close_accordion_section() {
$('.accordion .accordion-section-button').removeClass('active');
$('.accordion .accordion-section-content').slideUp(300).removeClass('open');
}
$('.accordion-section-button').click(function(e) {
// Grab current anchor value
var currentAttrValue = $(this).attr('href');
if($(e.target).is('.active')) {
close_accordion_section();
}else {
close_accordion_section();
// Add active class to section title
$(this).addClass('active');
// Open up the hidden content panel
$('.accordion ' + currentAttrValue).slideDown(300).addClass('open');
}
e.preventDefault();
});
});
Upvotes: 2
Views: 342
Reputation: 42054
If you like, you can reduce everything to:
$(document).ready(function() {
$('.accordion-section-button').click(function(e) {
close_accordion_section();
$(this).toggleClass('active');
$('.accordion ' + this.attributes.href.value)[(this.classList.contains('active')) ? 'slideDown' : 'slideUp'](300)
.toggleClass('open');
e.preventDefault();
});
});
Upvotes: 0
Reputation: 29092
The main problem is this line:
if($(e.target).is('.active')) {
When you click on the <h3>
the element e.target
will be the <h3>
and not the <a>
. Instead try something like this:
if($(this).is('.active')) {
Note that this is now consistent with the line where you add that class further down.
Upvotes: 1